Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get() takes from 2 to 3 positional arguments but 4 were given. Why is this error occuring? What is the solution for this?
I was working on a comment of a blog project. When I typed the code to handle the POST request in the views.py but was getting a error. This was the error 'get() takes from 2 to 3 positional arguments but 4 were given'. models.py class commenttable(models.Model): comment_id = models.AutoField(primary_key=True, default=0) blog = models.TextField() comment_name = models.CharField(max_length=200) comment_email = models.EmailField() comment_Text = models.TextField() comment_date = models.DateField() def __str__(self): return self.comment_Text views.py from .models import commenttable ... def post_comment(request, blog_id): if request.method == 'POST': data = request.POST.get("name", "email", "comment") # blog = get_object_or_404(Blog_tables, pk=blog_id) p = commenttable(blog= data.name, comment_name=data.email, comment_email= data.email, comment_Text= data.comment, comment_data = timezone.now()) p.save() return HttpResponseRedirect('/thanks/') else: return render(request, '/blogs/' + blog_id + '/comment', {'error_message': 'Error'}) This is the form : <form action="/blogs/{{blog_id}}/comment" method ="post"> {% csrf_token %} <input type="text" name="name" id="name" placeholder="Enter Your Name"/> <input type="text" name="email" id="email" placeholder="Enter Your Email"/> <input type="text" name="comments" id="comments" placeholder="Comments here"/> <input type="submit" value="Post"/> </form> I want to get the data from POST request and save it to the database. But writing this code gives me error 'get() takes from 2 to 3 positional arguments but 4 were given'. -
I m confused about the ready function used inside app.py
i m doing some project using django frame work i am a beginner and just used django signals but i m confused that why do we need to imporrt signals file in app.py inside the ready function code below makes question more clear i m stuck in this so require help signal.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save,sender=User) def create_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save,sender=User) def save_profile(sender,instance,**kwargs): instance.profile.save() app.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals #i have no idea what this function does what is the need of ready function here and why is it importing signals here??? -
How to rollback to a transaction made by django default, in MySQL?
so I have a django app using MySQL database, the client asked for some database records deletions, and one of our developers did the deletions manually from the MySQL console, now I'm trying to recover it to the previous state, I don't have any backups, I read that django does transactions automatically by default,so I want to know how can I rollback to one of these transactions. I already seen this and this, none of them helped me. -
How to correctly write url for #hashtag in Django
I want to insert data with modal form and show it on current page. Page already show data on table and modal form, now i need to add modal form to urls.py. path('viewpost/#add_data_Modal', views.createpost, name='createpost'), -
Error log PythonAnywhereDjango Python PythonAnywhere
Why does hosting on pythonanywhere not work? The syntax seems to me to be correct? Everything works fine on my computer. http://fixitcemes.pythonanywhere.com/ https://www.pythonanywhere.com/user/fixitcemes/files/var/log/fixitcemes.pythonanywhere.com.error.log models.py class Device(models.Model): """Model representing a device.""" type_name = models.ManyToManyField(DeviceType, help_text='Select a device type') device_id = models.DecimalField(max_digits=4, decimal_places=0) short_name_device_own = ForeignKey(DeviceType, related_name='device_type_device', on_delete=models.SET_NULL, null=True) prod_year = models.DateTimeField(auto_now=False, auto_now_add=False) worked_science = models.DateField(auto_now=False) def __str__(self): """String for representing the Model object.""" return f'{self.short_name_device_own} - {self.device_id}' error log: 2019-10-13 10:05:37,509: Error running WSGI application 2019-10-13 10:05:37,510: File "/home/fixitcemes/fixitcemes.pythonanywhere.com/mysite/dokumenty/models.py", line 38 2019-10-13 10:05:37,510: 2019-10-13 10:05:37,511: return f'{self.short_name_device_own} - {self.device_id}' 2019-10-13 10:05:37,511: 2019-10-13 10:05:37,511: ^ 2019-10-13 10:05:37,511: 2019-10-13 10:05:37,511: SyntaxError: invalid syntax 2019-10-13 10:05:37,511: File "/var/www/fixitcemes_pythonanywhere_com_wsgi.py", line 15, in <module> 2019-10-13 10:05:37,512: application = get_wsgi_application() 2019-10-13 10:05:37,512: 2019-10-13 10:05:37,512: File "/home/fixitcemes/.virtualenvs/fixitcemes.pythonanywhere.com/lib/python3.5/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2019-10-13 10:05:37,512: django.setup(set_prefix=False) 2019-10-13 10:05:37,512: 2019-10-13 10:05:37,512: File "/home/fixitcemes/.virtualenvs/fixitcemes.pythonanywhere.com/lib/python3.5/site-packages/django/__init__.py", line 24, in setup 2019-10-13 10:05:37,513: apps.populate(settings.INSTALLED_APPS) 2019-10-13 10:05:37,513: 2019-10-13 10:05:37,513: File "/home/fixitcemes/.virtualenvs/fixitcemes.pythonanywhere.com/lib/python3.5/site-packages/django/apps/registry.py", line 114, in populate 2019-10-13 10:05:37,513: app_config.import_models() 2019-10-13 10:05:37,514: 2019-10-13 10:05:37,514: File "/home/fixitcemes/.virtualenvs/fixitcemes.pythonanywhere.com/lib/python3.5/site-packages/django/apps/config.py", line 211, in import_models 2019-10-13 10:05:37,514: self.models_module = import_module(models_module_name) 2019-10-13 10:05:37,514: *************************************************** 2019-10-13 10:05:37,514: If you're seeing an import error and don't know why, 2019-10-13 10:05:37,515: we have a dedicated help page to help you debug: 2019-10-13 10:05:37,515: https://help.pythonanywhere.com/pages/DebuggingImportError/ -
Django unit tests ask to delete MariaDB DB: (1007, "Can't create database 'test_x_django'; database exists")
I have django unit tests creating a MariaDB database for tests. I am accessing the database with a user and password in the settings file and keep getting this error: Type 'yes' if you would like to try deleting the test database 'test_x_django', or 'no' to cancel: Got an error creating the test database: (1007, "Can't create database 'test_x_django'; database exists") Which makes me type 'yes' every time that I run unit tests - specifically after stopping tests in the middle (not allowing django to delete the database?). I have tried a lot of solutions, including: trying to use the root user, giving django_user all permissions to 'test_x_django' db, giving django_user permissions to createdb. I have not found a solution online for MariaDB, in this case. The configuration in my settings.py file is: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'x_django', 'USER': 'django_user', 'PASSWORD': 'xxxx', 'HOST': 127.0.0.1, 'PORT': '3306' } } Is there a solution to make django stop asking the question, and delete the Database automatically? -
DRF: "GET Not Allowed", on a generic view set with ListModel mixin
I have 2 viewsets on the same url, one for Create and List the other one for retrieve update and destroy. The Viewset Code is follows class UserViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): """ retrieves user accounts """ queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) class UserCreateViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): """ Creates user accounts """ queryset = User.objects.all() serializer_class = CreateUserSerializer permission_classes = (AllowAny,) def list(self, request, *args, **kwargs): email = self.request.query_params.get('email', None) phone_no = self.request.query_params.get('phone_no', None) if email is not None: queryset = User.objects.filter(email=email) elif phone_no is not None: queryset = User.objects.filter(phone_no=phone_no) else: queryset = User.objects.all() return super(UserCreateViewSet, self).list(request, *args, **kwargs) This is my url configuration: router = DefaultRouter() router.register(r'users', UserCreateViewSet) router.register(r'users', UserViewSet) router.register(r'advertisement', AdvertisementCreateViewSet) router.register(r'advertisement', AdvertisementViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api-token-auth/', CustomAuthToken.as_view()), path('api-token-auth/verify-otp', VerifyTokenView.as_view()), path('api-token-auth/verify-email', VerifyEmailView.as_view()), path('api/v1/admin/login', LoginAdminUser.as_view()), path('api/v1/user/reset-password/', ResetPasswordView.as_view()), url('api/v1/user/(?P<id>.+)/changePassword', ChangePasswordView.as_view()) path('api/v1/', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), re_path(r'^$', RedirectView.as_view(url=reverse_lazy('api-root'), permanent=False)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The advertisement ViewSet does the exact same thing on a different model and it works seemlessly. But in the UserViewSet it doesn't..I tried comparing the code of both viewsets and they are exactly the same.... -
django user authentication and authorization
I need suggestion on the following issue, actually I start developing a small erp in django. I’m quite confuse about how to handle user authentication and authorization. My project architecture is ERP (Main Project) o HR (App) o Finance (App) o Payroll (App) o Sale (App) How to implement login system in above architecture? Thanks -
Getting JSON out of JSONfield in django
I'm using Django rest framework 3.9.1 and am trying to get just the JSON, in JSON format, from a JSONfield. My model looks like: class Metadata(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) data = JSONField() def __str__(self): return "%s %s" % (self.id) but when I get the data through an endpoint by calling: Metadata.objects.values('data') I get: [ { "data": "{\"name\":\"test1\"}" }, { "data": "{\"name\":\"test2\"}" } ] How do I return the raw JSON in the JSONfield in JSON format? so like: [ { "name":"test1" }, { "name":"test2" } ] -
Django http site serves media files but https site does not
Serving django media files on http site is OK. Serving django media files on https site is not working. I have the copied the alias and directories from the myproject_http.conf to myproject_https.conf. The media files are served on http site without any problems. HTTP conf: <VirtualHost *:80> ServerAdmin myproject.co@gmail.com DocumentRoot /home/ubuntu/bulbasaur/bulbasaur/ ServerName myproject.net ServerAlias www.myproject.net ErrorLog ${APACHE_LOG_DIR}/myproject_error.log CustomLog ${APACHE_LOG_DIR}/myproject_access.log combined Alias /media/ /home/ubuntu/bulbasaur/bulbasaur/media/ Alias /static/ /home/ubuntu/bulbasaur/bulbasaur/static_root/ <Directory /home/ubuntu/bulbasaur/bulbasaur/alpha> <Files wsgi_myproject.py> Require all granted </Files> </Directory> <Directory /home/ubuntu/bulbasaur/venv> Require all granted </Directory> <Directory /home/ubuntu/bulbasaur/bulbasaur/media> Require all granted </Directory> <Directory /home/ubuntu/bulbasaur/bulbasaur/static_root> Require all granted </Directory> WSGIDaemonProcess myproject.net python-home=/home/ubuntu/bulbasaur/venv/ python-path=/home/ubuntu/bulbasaur/bulbasaur/ WSGIScriptAlias / /home/ubuntu/bulbasaur/bulbasaur/alpha/wsgi_myproject.py process-group=myproject.net WSGIProcessGroup myproject.net </VirtualHost> HTTPS conf: <IfModule mod_ssl.c> <VirtualHost *:443> ServerAdmin myproject.co@gmail.com DocumentRoot /home/ubuntu/bulbasaur/bulbasaur/ ServerName myproject.net ServerAlias www.myproject.net ErrorLog ${APACHE_LOG_DIR}/myproject_error.log CustomLog ${APACHE_LOG_DIR}/myproject_access.log combined Alias /media/ /home/ubuntu/bulbasaur/bulbasaur/media/ Alias /static/ /home/ubuntu/bulbasaur/bulbasaur/static_root/ <Directory /home/ubuntu/bulbasaur/bulbasaur/alpha> <Files wsgi_myproject.py> Require all granted </Files> </Directory> <Directory /home/ubuntu/bulbasaur/venv> Require all granted </Directory> <Directory /home/ubuntu/bulbasaur/bulbasaur/media> Require all granted </Directory> <Directory /home/ubuntu/bulbasaur/bulbasaur/static_root> Require all granted </Directory> WSGIDaemonProcess myproject.net python-home=/home/ubuntu/bulbasaur/venv/ python-path=/home/ubuntu/bulbasaur/bulbasaur/ WSGIScriptAlias / /home/ubuntu/bulbasaur/bulbasaur/alpha/wsgi_myproject.py process-group=myproject.net WSGIProcessGroup myproject.net Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateFile /etc/letsencrypt/live/myproject.net/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/myproject.net/privkey.pem </VirtualHost> </IfModule> May I know what I got wrong? -
Django API - XMLHttpRequest cannot load
I get a XMLHttpRequest cannot load www.mysite.com/api-data due to access control checks. I have set up an api on my website and now I want to stream data from it. How can I solve this issue? Thanks -
ssl certificate for django project on heroku
I am learning how to create a app using django. i deployed my app on heroku(without credit card). now i need to add the functionality to sign up using any social media like github, but i am getting 'ERR_SSL_PROTOCOL_ERROR'. i tried getting free ssl certificate from CloudFlare but adding my webiste url 'https://udaydjangoproject.herokuapp.com' shows invalid domain and then i tried 'udaydjangoproject.herokuapp.com', then it shows not a registered domain. I don't have any credit card/debit card. is there any way to get get free ssl certificate from anywhere? -
NoReverseMatch at / Django template rendering
I have this problem and been stuck for few hours. NoReverseMatch at / Reverse for 'hotovo' with arguments '('',)' not found. 1 pattern(s) tried: ['hotovo/(?P[^/]+)$']. urls: urlpatterns = [ path('', views.index, name='index'), path('hotovo/<jedlo_id>', views.hotovo, name='hotovo') ] views: def hotovo(request, jedlo_id): jedlo = VyberJedla.objects.get(pk=jedlo_id) jedlo.vybrane = True jedlo.save() return redirect('') html: <h1><a href="{% url 'hotovo' jedlo.id%}" class="este_nie"> {{zoznam.nazov_jedla}}</a><input type="checkbox" name="cekbox"> . -
Which is a best book to start learning Django?
I want to learn more about how django handles databases, could you plz recommend me a good book for that..... -
Override function without if statement
Three models have ImageField which refers to one function, with if. Is there any suggestions how to perform this function without if? def upload_location(instance, filename): _, extension = os.path.splitext(filename) if isinstance(instance, (Story,)): return f'stories/{instance.id}/cover{extension}' elif isinstance(instance, (Episode,)): return f'stories/{instance.story.id}/{instance.index}/cover{extension}' elif isinstance(instance, (EpisodeSlide,)): return f'stories/{instance.episode.story.id}/{instance.episode.index}/{instance.id}{extension} -
How to use in Django a register form made with html and css
I have a responsive register and login made with HTML and CSS. I don't want to use the common register form and login that Django creates when you configure it. Summarizing my problem, I know how to make the register form in Django and configure it but I don't know how to apply my template on it. I've been reading about how to use templates on django but I still didn't figure out on how to use correctly in my case. My register html <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://fonts.googleapis.com/css?family=Manjari&display=swap" rel="stylesheet"> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <link rel="stylesheet" href="reg.css"> <title>Document</title> </head> <body> <div class="back"></div> <div class="registration-form"> <header> <h1>Registrarse</h1> <p>Completa la información</p> </header> <form> <div class="input-section email-section"><input class="email" type="email" placeholder="Ingresa tu EMAIL aquí" autocomplete="off" /> <div class="animated-button"><span class="icon-paper-plane"><i class="fa fa-envelope-o"></i></span><span class="next-button email"><i class="fa fa-arrow-up"></i></span></div> </div> <div class="input-section password-section folded"><input class="password" type="password" placeholder="Ingresa tu CONTRASEÑA aquí" /> <div class="animated-button"><span class="icon-lock"><i class="fa fa-lock"></i></span><span class="next-button password"><i class="fa fa-arrow-up"></i></span></div> </div> <div class="input-section repeat-password-section folded"><input class="repeat-password" type="password" placeholder="Repita la CONTRASEÑA" /> <div class="animated-button"><span class="icon-repeat-lock"><i class="fa fa-lock"></i></span><span class="next-button repeat-password"><i class="fa fa-paper-plane"></i></span></div> </div> <div class="success"> <p>CUENTA CREADA</p> </div> </form> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="reg.js"></script> </body> </html> -
Django model name with underscore?
I have subtly different entities that are important enough with respect to the relationships, flexibility, and expression of my schema that they warrant separate models. How should I name/ case these? a) Layerinput, Layerhidden, Layeroutput b) Layer_Input, Layer_Hidden, Layer_Output c) LayerInput, LayerHidden, LayerOutput Right now I am leaning option a so that Django doesn't do anything too automagically incorrect with them, but that won't look great in documentation and code. Will use them with either DRF or graphql. -
Why can't I find my static folder in my project
I'm working on a Django project and I can't see my static folder, I'm also having a problem displaying images. And when I inspect the image div in the src it's written unknown, Here's how I display the image from the admin ``<img class="rounded-circle account-profile" src="{{ user.Profile.profile_photo.url }}" alt="profile">`` User is the current user, the profile and then the name of the column. My folder structure is route-folder( project-folder, media-folder and app-folder ) My static settings ```STATIC_URL = '/static/' SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) STATICFILES_DIRS = [ os.path.join(SITE_ROOT, "static/"), ]``` The Url: ```if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Daphne error __call__() got an unexpected keyword argument 'scope' using systemctl
I'm running Daphne using systemctl and when doing sudo systemctl start daphne I'm getting this Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: 2019-10-12 19:43:08,907 ERROR [Failure instance: Traceback: <class 'TypeError'>: __call__() got an unexpected keyword argument 'scope' Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: /home/ubuntu/django_apps/startmexico/startmexicoenv/lib/python3.6/site-packages/autobahn/websocket/protocol.py:2801:processHandshake Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: /home/ubuntu/django_apps/startmexico/startmexicoenv/lib/python3.6/site-packages/txaio/tx.py:429:as_future Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: /home/ubuntu/django_apps/startmexico/startmexicoenv/lib/python3.6/site-packages/twisted/internet/defer.py:151:maybeDeferred Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: /home/ubuntu/django_apps/startmexico/startmexicoenv/lib/python3.6/site-packages/daphne/ws_protocol.py:82:onConnect Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: --- <exception caught here> --- Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: /home/ubuntu/django_apps/startmexico/startmexicoenv/lib/python3.6/site-packages/twisted/internet/defer.py:151:maybeDeferred Oct 13 00:43:08 ip-172-31-18-50 daphne[24358]: /home/ubuntu/django_apps/startmexico/startmexicoenv/lib/python3.6/site-packages/daphne/server.py:200:create_application daphne.service [Unit] Description=daphne service After=network.target [Service] WorkingDirectory=/ProjectDir Environment=DJANGO_SETTINGS_MODULE=settings.prod ExecStart=/ProjectDir/env/bin/daphne -b 0.0.0.0 -p 8001 config.wsgi:application Restart=always [Install] WantedBy=multi-user.target Module versions channels 2.3.0 Twisted 19.7.0 redis 2.10.6 daphne 2.3.0 The interesting part is that if I run manually from the env daphne -b 0.0.0.0 -p 8001 config.asgi:application` it's working without errors. Also if I change in daphne.service this line ExecStart=/ProjectDir/env/bin/daphne -b 0.0.0.0 -p 8001 config.wsgi:application to ExecStart=/ProjectDir/env/bin/daphne -p 8001 config.wsgi:application the error is not show, but of course the connection is not stablished. Any clue? -
How to get all Posts from Communities that User has joined in Django REST
So I have a User model, Community model, Post model and UserJoinedCommunity model. What I want to do is get all Posts from Communities that User has joined so I can display them on home page. UserJoinedCommunity model that controlls which user has joined which community: class UserJoinedCommunity(models.Model): """DB Model for users joined communities""" user = models.ForeignKey(User, on_delete=models.CASCADE) community = models.ForeignKey(Community, on_delete=models.CASCADE) class Meta: constraints = [ UniqueConstraint(fields=['user', 'community'], name="user-joined-community") ] def __str__(self): return f"{self.user.username}|{self.community.name}" Community and Post models are just simple models with fields like name, title etc. So now I would like to create a APIView or ViewSet that would return all posts from communities that user has joined. Something like this: class UserRelevantPosts(APIView): authentication_classes = (TokenAuthentication,) def get(self, request): user_relevant_posts = "?" return Response({'posts': user_relevant_posts}, status=200) Tell me if you need more code samples. -
How to display something in the web page when downloading file in Django
I am very very new to Django and i am getting my feet wet with it. I have a use case in which i want the user to download a file when they go to the home page of the Django website but at the same time i want to show some text as well. Below is the definition of my view: from django.http import HttpResponse def home(request): my_data = "<h1>This will be an attachement to download!</h1>" response = HttpResponse() response.content = my_data response['Content-Disposition'] = 'attachment; filename="<some-file>"' return response The issue is the file is getting downloaded but i cannot see anything getting printed to the screen . I mean i need this message (This will be an attachement to download!) to also be in the screen . I am sure i am doing some simple mistake but i cannot figure out what it is. Can someone please help me. -
Real-time Geolocation Tracking
I'm using the google maps javascript API to render a map. I'm using Python's Django v2 but the actual code for the API interaction and map creation is just Javascript. The client has have a fleet of trucks and I'd like to suggest a new feature: tracking the trucks' real-time location on the map. If each of the trucks had an tablet I imagine I could somehow get near-real-time geolocation information from that device. Question: Should I be trying to send geolocation info from the tablets to the server (if so how?) or should I be trying to GET/retrieve the geolocation from the tablets (if so how?)? Thinking of apps like Uber or Lyft what is the best practice/tried-and-true protocol to use with IOT & geolocation? -
Using PostgreSQL Arrayfield as ManyToMany -like lookup?
I have two models: class Authors(models.Model): name = models.CharField() class Books(models.Model): title = models.CharField() author_ids = ArrayField(Integerfield()) I would like to be able to look about the authors of the books by doing books.authors. Is there some way to do this? I can't seem to find a way to do this. This database is already prepopulated with the author_ids so reworking it to something else, like using an intermediary table, would be difficult. -
Django model allow multiple
So I want to create a model, let's say "Cars" I want to implement the field detail_name and detail_desc detail_name = models.CharField(max_length=200) detail_desc= models.CharField(max_length=200) But I want an admin to be able to add another detail_name and detail_desc if they wish to. How can I implement that? -
Inserting a Django URL into a custom email template
I'm trying to send a Django email in a custom template that I made for my site. However, I can't get the Django URL link to work properly. Without the template, I can get the link to work. The username works for reference. Does anyone know how to make this work? Here is my views.py: #This code is in the view that sends the email from django.core.mail import EmailMessage from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template from django.template import Context subject, from_email = 'subject', '<info@mysite.com>' plaintext = get_template('email.txt') htmly = get_template('email.html') username = user.username d = { 'username': username } text_content = plaintext.render(d) html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, text_content, from_email, [user.email]) msg.attach_alternative(html_content, "text/html") msg.send() This setup is based on this answer: Creating email templates with Django Here is the email.html file: <h3>Hi <strong>{{ username }}</strong>,</h6> <p> disown kvdsvnsdov vknvisodvnsdv dsdov siod vsd. Here is a link:</p> <a href="http://domain{% url 'home' %}">Check Now</a> Here is the email.txt: Hi {{ username }}, disown kvdsvnsdov vknvisodvnsdv dsdov siod vsd. Here is a link: http://domain{% url 'home' %}