Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django blog post with group restriction
I'm wondering how to implement group permission settings to django form. I'm developing a membership blog system. In the system, there will be three types of users. 1. premium users 2. normal users 3. not loggined users Only loggined (is_authenticated, thus, both premium and normal) users can post a new blog entry. For premium users, when posting a new entry, I want to give options below. -Show only for premium users. -Show only for loggined (both premium and normal) users. -Public (not loggined users also can read the post). For normal users, when posting a new entry, I want to give options below. -Show only for loggined (both premium and normal) users. -Public (not loggined users also can read the post). For the membership, I will use django default django.contrib.auth.models.Group. But I have not idea how to implement the options into blog post form. Now I use generic.CreateView, but is it necessary to create form scratch? Even so, I can't figure out how to associate the group participation status for loggined user. Anyway please give me some advice. regards, #models.py from django.db import models from config.common import AUTH_USER_MODEL class Theme(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='theme_user') title = models.CharField(max_length=150, blank=True, null=True) … -
how to use django html filters
I was making a project for my college, it requires me to make a social media kind of site for the college I wanted to add a page that displays all the users and gives an button next to each user to follow them. if we are following them the button next to their name will say unfollow and vice versa. I was wondering how can I make check wether I follow a user or not in the html. code models.py class Following(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) users_ifollow=models.ManyToManyField(User, related_name='followed_by',blank=True, null=True) people_followme=models.ManyToManyField(User, related_name='peeps',blank=True, null=True) def __str__(self): return f'{self.user.username} following' def redirect_route(username): return reverse('user-posts',args=[str(username)]) class Portfolio(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) category=models.CharField(max_length=20, blank=True) image1=models.ImageField(upload_to='profile_pics',blank=True) image2=models.ImageField(upload_to='profile_pics',blank=True) image3=models.ImageField(upload_to='profile_pics',blank=True) image4=models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): return f'{self.user.username} Portfolio' views.py def user_list(request): authors=Portfolio.objects.all() context={'author':authors} return render(request, 'blog/userlist.html',context) html {% if user in u.followed_by %} <a class='mr-2' href='#'><button class='btn btn-danger'>Unfollow</button></a> {% endif %} <div class=''> -
How to disable django recapture for testing or anything?
How to disable django recapture for testing?.I'm using django-recaptcha==1.0.2 -
how to use filters in html for django models
I was making a project for my college, it requires me to make a social media kind of site for the college I wanted to add a page that displays all the users and gives an button next to each user to follow them. if we are following them the button next to their name will say unfollow and vice versa. I was wondering how can I make check wether I follow a user or not in the html. code models.py class Following(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) users_ifollow=models.ManyToManyField(User, related_name='followed_by',blank=True, null=True) people_followme=models.ManyToManyField(User, related_name='peeps',blank=True, null=True) def __str__(self): return f'{self.user.username} following' def redirect_route(username): return reverse('user-posts',args=[str(username)]) class Portfolio(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) category=models.CharField(max_length=20, blank=True) image1=models.ImageField(upload_to='profile_pics',blank=True) image2=models.ImageField(upload_to='profile_pics',blank=True) image3=models.ImageField(upload_to='profile_pics',blank=True) image4=models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): return f'{self.user.username} Portfolio' views.py def user_list(request): authors=Portfolio.objects.all() context={'author':authors} return render(request, 'blog/userlist.html',context) html {% if user in u.followed_by %} <a class='mr-2' href='https://www.grayocean.co/user/{{u.user}}/follow'><button class='btn btn-danger'>Unfollow</button></a> {% endif %} <div class=''> -
How do I create a button that sends an HTTP GET request to a secure URL when clicked?
I am building a web app where a user searches for a camera (located on a remote network with a dyndns domain) and is shown a button to trigger a siren on the camera. When the user clicks the button, they should not see the page refresh or anything happen (other than the button maybe being disabled). The button is sending an HTTP GET request to the website example.com:port/abc.xml?relay2State=2. However, I'm unsure how to handle when the user refreshes or hits the back button, and how the browser stores the request in its history. I don't want the user to be able to press the back button and activate this request again, or refresh the page and activate it. Neither should the user be able to save the button request as a bookmark. Essentially, this event should only be able to fire off when the button is clicked. This led to the question: should this be a GET or POST request, and how do I incorporate it via button? Here is the relevant HTML code: <!-- siren_search.html --> {% if cameras %} <button id="trigger-all-btn" type="button" class="btn btn-lg btn-block btn-outline-danger btn-space">Trigger all sirens</button> <table id="camera-table" class="table table-hover"> <thead> <tr class="header"> <th … -
Using request.body in Django compared to nodejs for building restful apis
I have just begun learning the Django framework, and my goal is too take this knowledge and use it to build a rest api. (I have considered using django-rest framework, but my job requires specifically Django). I have already learned a medium amount of nodejs, and for this I use express. I use the req.body to enable users to enter some information. In Django, how would I use this req.body property to allow a user to type information. This is purely for backend purposes (no frontend included). -
How on the server to get data from formData that was placed there through the serialize?
I put the data from the form in the formData. Added an image there. After passing them to the server in the post request. But the problem is that I do not know how to properly handle them. I can write some kind of crutch to handle the string, but not hunting. Are there any more humane methods? If I put the processData = True in the ajax request, then I get the error Uncaught TypeError: Illegal invocation request var main_form = $('form').serialize(); #data from form var image = $("#id_image").prop("files")[0]; #image from form var form = new FormData(); form.append("form", main_form); form.append("main_image", image); $.ajax({ headers: {'X-CSRFToken': '{{ csrf_token }}' }, type: 'POST', url: event.target.action, data: form, processData: false, contentType: false, cache: false view def get_context_data(self, *args, **kwargs): ctx=super(ProductsCreate, self).get_context_data(*args, **kwargs) ctx['special_form'] = SpeciallyPriceForm() return ctx def post(self, request, *args, **kwargs): print(request.POST) #<QueryDict: {u'form' [u'csrfmiddlewaretoken=g1eaQ1DxGmlFTfTG0g5c0JSMUehF3wYfquWNdeT2SQzlp2LWCpQbIsleWXMsCHKB&on_behalf=4&type=product&title=1&product_code=1&category=1&product_type=usual&status=show&lot_minimum=1&lot_type=1&weight=1&lot_amount=1&lot_cost=1&lot_currency=1&adittional_specially_number=1&adittional_specially_price=1&adittional_specially_number=&adittional_specially_price=&BLAGO=0.0&platform_fee=10.00&content=']}> print(request.FILES) #<MultiValueDict: {u'main_image': [<InMemoryUploadedFile: robot.jpeg (image/jpeg)>]}> form = ProductCreateForm(request.POST, request.FILES, initial={'request': request}) special_form = SpeciallyPriceForm(request.POST) print(form) #empty template print(dir(form)) #['Meta', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__html__', '__init__', '__iter__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', '_bound_fields_cache', '_clean_fields', '_clean_form', '_errors', '_get_validation_exclusions', '_html_output', '_meta', '_post_clean', '_save_m2m', … -
Django - Using get_form with get_form_class
I have this working: class DashboardView(LoginRequiredMixin, LanguageMixin, FormView): template_name = 'dashboard.html' form_class = UserSettingsForm def get_form(self, form_class=form_class): return form_class(instance=self.request.user, **self.get_form_kwargs()) It correctly assigns the user object to the form. However, I have made a duplicate form that provides translated versions of the form labels if the user has opted for this. def get_form_class(self): form_class = UserSettingsForm if self.request.session['language'] != 0 or self.request.user.site_language != 0: form_class = TranslatedUserSettingsForm return form_class What I can't figure out how to do is plug in the user object via get_form I've tried just doing this: def get_form(self, form_class=None): return self.get_form_class(instance=self.request.user, **self.get_form_kwargs()) As well as messing around with super, but I'm not figuring it out. What am I missing? Forms are below: class UserSettingsForm(ModelForm): class Meta: model = ListenUser fields = ['allows_contact_email', 'allows_contact_sms', 'phone_number', 'email'] labels = LABELS class TranslatedUserSettingsForm(ModelForm): class Meta: model = ListenUser fields = ['allows_contact_email', 'allows_contact_sms', 'phone_number', 'email'] labels = get_label_translations() -
Cloudinary direct upload documentation example is not clear
In Cloudinary Django SDK documentation for direct from browser uploading it gives example below for direct_upload_complete view. @csrf_exempt def direct_upload_complete(request): form = PhotoDirectForm(request.POST) if form.is_valid(): form.save() ret = dict(photo_id = form.instance.id) else: ret = dict(errors = form.errors) return HttpResponse(json.dumps(ret), content_type='application/json') Immediately after this example it says Having stored the image ID, you can now display a directly uploaded image in the same way you would display any other Cloudinary hosted image: and gives template code example as follows: {% load cloudinary %} {% cloudinary photo.image format="jpg" width=120 height=80 crop="fill" %} I am confused by this template code example because it does not relate at all to the Django view code which has response name ret What Javascript is required to create a variable from the JSON object named ret and display it on the template page? -
How can i generate a page dynamically in Django?
I'm building a site in Django but i'm kind of stuck with the following problem. In my home.html i have a list which looks something like this: {% extends "main/header.html" %} {% block content %} <body> <div class="itemlist"> <ul> <li><a href="item1">Item 1</a></li> <li><a href="item2">Item 2</a></li> <li><a href="item3">Item 3</a></li> <li><a href="item4">Item 4</a></li> </ul> </div> </body> {% endblock %} This list is updated dynamically, so there will be more and different items. This is what i'm trying to do: for each of those items, when i open the item's link, a new page should be opened, containing data about the item, like this: site.com/item1, or site.com/item2 The problem: i can't create a view and a template for each item, since the list will grow. Creating a view, a template and a url for each is not a doable solution. A possible approach: create a view that generates a standard page and append the link to that page, like this: site.com/items/item-here, so for example site.com/items/item15 The problem is that i'm fairly new to Django, so i don't know how to apply this approach practically. Can someone give me an hint on where i should go from here? Every advice is appreciated. I hope … -
Request object has no attribute 'oauth2_error' in DRF + DOT
I'm using djangorestframework and django-oauth-toolkit for my API. I have a fairly simple user logout view, which supports both DOT logout with token revoking and regular Django session logout: class UserLogoutView(APIView): permission_classes = (IsAuthenticated,) @staticmethod def post(request): token = request.data.get('access_token') logout(request) if not token: return Response('OK') client_id = request.data.get('client_id') try: app = Application.objects.get(client_id=client_id) except Application.DoesNotExist: raise AuthenticationFailed('Invalid client_id') client_secret = app.client_secret r = requests.post(settings.OAUTH_URL.format('revoke-token'), data={ 'client_id': client_id, 'client_secret': client_secret, 'access_token': token, }) if r.status_code != 200: raise AuthenticationFailed('Failed to revoke token') return Response(r.json()) When I send invalid client_id I expect to get a 401 response with error, but instead I get an error (which is the result of raising AuthenticationFailed as states the traceback): AttributeError: 'Request' object has no attribute 'oauth2_error' I suppose something is wrong with exception handling of DRF + DOT combination, but how to fix it? -
djago.mo djago.po loop while deploying
so I finished my first app and about to upload to the world but when I try to copy my file to ssh server I get django.mo and django.po loop. I did scp -r django_project myapp@ipnumber:~/ -
Django EmailMultiAlternatives throws Connection unexpectedly closed on send
I am using godaddy mail for send mails from my django backend but it is giving me "Connection unexpectedly closed". My code goes as follow: views.py current_site = get_current_site(request) subject = 'Welcome to MySite! Confirm Your email.' htmly = get_template('account_activation_email.html') d = { 'user': user, 'domain':current_site.domain, 'uemail':urlsafe_base64_encode(force_bytes(user.email)), 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user)} text_content = "" html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, text_content, '', [user.email]) msg.attach_alternative(html_content, "text/html") try: msg.send() except BadHeaderError: print("Error while sending email!") user.save() setting.py EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend' EMAIL_USE_SSL = True # EMAIL_USE_TLS = True EMAIL_HOST = config('EMAIL_HOST') EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') EMAIL_PORT = 465 SERVER_EMAIL = 'verify@mysite.com' DEFAULT_FROM_EMAIL = 'Verification <verify@mysite.com>' Please help me... -
Using dictionary to print values to HTML table creates empty table
I'm trying to render a table in a webpage using a dictionary of dictionaries. Seems like a simple enough task, but so far I've had no success. So far, I've tried the following code: Template: <table> <thead> <tr> <th>Email</th> <th>Name</th> <th>Workplace</th> <th>Contact Number</th> <th>User type</th> </tr> </thead> <tbody> {% for key,value in contacts.items %} <tr> <td>{{ key }}</td> <td>{{ value.name }}</td> <td>{{ value.workplace }}</td> <td>{{ value.contact }}</td> <td>{{ value.user_type }}</td> </tr> {% endfor %} </tbody> </table> And my contacts is of the following format: { 'webum@cryptonet.top': {'workplace': 'SRK Films', 'user_type': 'company', 'name': 'SRK', 'contact': '-'}, 'zojisopeyu@crypto-net.club': {'user_type': 'campus', 'workplace': 'bchjb', 'contact': '1478529631', 'name': 'Pry'} } I'm sending the variable to template through the following: return render(request, 'maintainer/mcontact.html',contacts) All I'm getting is the header cells that I explicitly wrote. The rest of the table data is empty. It shows a "No data available in table" message. I'm printing contacts to stderr so I know the variable has the correct values. Am I missing something else? I don't understand what else I should do. Any help is appreciated since I'm very new to Django. -
Django - Sending email with sendgrid templates - problem with a from address
I am using Sendgrid Dynamic Transactional Templates to send emails from my django project. The code can be seen below. sg = SendGridAPIClient(djangoSettings.SENDGRID_KEY) message = Mail( from_email = some@email, to_emails=some@email, ) message.dynamic_template_data = {... } message.template_id = '....' response = sg.send(message) The email sends fine, but I need to use a from_email to send. I don't want to use an email they can reply to. I want some generic email associated with my sendgrid account, lets say mydomain.com. How can I go about solving that? -
How to write select query in django in chain of one-to-many relationship?
How to write select query in django? I have 2 one-to-may relationship At the beginning, i am not very good at english. i am so sorry :). I have 3 tables. Driver, Car and Ride. The relationship between Driver and Car is (one-to-many: a Driver can have multiple Car. The relationship between Car and Ride is (one-to-many: a Car can have multiple Ride. I want list of drivers who have x times of rides. I expect something like this: <QuerySet [<Driver: 1>, <Driver: 2>]>which is Drivers with greater than or equal x Rides -
How to view data that is foreign key through ajax. Read description for then you will better understand
this is my view.py file. a small part where i m having doubt from django.http import HttpResponse from django.shortcuts import render from django.shortcuts import redirect from django.contrib.sessions.models import Session from .models import * from django.http import JsonResponse def getHodData(request): hh = list(HODM.objects.all().values()) data = { "HodData" : hh, } return JsonResponse(data) this is my models.py file. i always like to put M at the end of model. from django.db import models class BranchM(models.Model): Bcode = models.IntegerField('bcode') Bname = models.CharField('bname', max_length=120) class UserM(models.Model): Uname = models.CharField('uname', max_length=120) class HODM(models.Model): Hname = models.CharField('hname', max_length=120) Hpassword = models.CharField('hpassword', max_length=16) UserM_id = models.ForeignKey(UserM, on_delete=models.CASCADE) BranchM_id = models.ForeignKey(BranchM, on_delete=models.CASCADE) this is my html file and has js inside it. function pqr() { $.ajax({ url: '/getHodData/', method: 'GET', datType:'JSON', success: function(data) { $('#app').html(''); data.HodData.forEach(room => { rows = ` <tr> <td>${room.id}</td> <td>${room.Hname}</td> <td>${room.BranchM_id_id}</td> //here i want to show Branch name <td> <button onclick="deletes(${room.id})" class="btn deleteBtn" data-id="${room.id}">Delete</button> <button onclick="updatedata(${room.id})" class="btn updateBtn" data-id="${room.id}" data-toggle="modal" data-target="#modal-7">Update</button> </td> </tr>`; $('#app').append(rows); }); }, failure: function(data) { alert('Got an error dude'); } }); } there is a table(html table) where i take all the Hod's data and view there. as in hod table(database table) there is a foreign key of branch. and … -
How to set up static files on different pages. Url issues
Sorry for my English. There was a problem with static files. I have a multi-page educational site. On the main page I connected the pictures. and on the second page I can’t do this because the first line of the URL goes exactly to the picture, and the second one goes through the other URL. models.py from django.db import models class Alex(models.Model): #first page class title = models.CharField(max_length=300, verbose_name = 'table of contents') titletwo = models.CharField(max_length=300, null=True, verbose_name = 'Description') content = models.TextField(null=True, blank=True, verbose_name='url img') foto = models.ImageField(blank=True, upload_to="images/body/%Y/%m/%d", help_text='150x150px', verbose_name='Ссылка картинки') class Meta: verbose_name_plural = 'body' verbose_name = 'body' class Bdtwo(models.Model): #for the second page title = models.CharField(max_length=300, verbose_name='table of contents') content = models.TextField(null=True, blank=True, verbose_name='Description') foto = models.ImageField(blank=True, upload_to="images/body/%Y/%m/%d", help_text='150x150px', verbose_name='url img') class Meta: verbose_name_plural = 'body2' verbose_name = 'body2' url.py - my project from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('blog/', include('blog.urls')), path('admin/', admin.site.urls), ] url.py-application rom django.urls import path from .views import * from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('', index), path('two', two) ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_URL = '/static/' MEDIA_ROOT … -
Django all-auth: Doesn't show First name and Last name while signing up for new accout
I am using Django-all auth for creating user accounts. I want to get First name, Last name, Email and Password while signing up. But Sign up page Doesn't show First name and Last name. Sign up page showing only Email and Password.Could someone help me with that? Please let me know if you need any other information. Thanks! Models.py class CustomUser(AbstractUser): # add additional fields in here first_name = models.CharField(max_length=128, blank=True, null=True) last_name = models.CharField(max_length=128, blank=True, null=True) def __str__(self): return self.email Forms.py class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('email','first_name','last_name') Signup.html <h2>Sign Up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign Up</button> </form> -
How do I get Django to treat my float number as a float instead of an int when it renders a query?
I'm using Python 3.7 and Django with PostGres 9.5. I have the following Django query qset = DomainTrackerStat.objects.annotate( result=F('num_negative_articles') / (F('num_negative_articles') + F('num_positive_articles')) ).filter(subreddit=subreddit, domain=domain, num_negative_articles__gt=settings.DOMAIN_NEGATIVE_ARTICLES_THRESHOLD, result__gt=settings.DOMAIN_NEGATIVE_ARTICLES_PCT) The constant, "settings.DOMAIN_NEGATIVE_ARTICLES_PCT" is ".95", but when my query gets rendered, the SQL appears as "0". If I make it "settings.DOMAIN_NEGATIVE_ARTICLES_PCT * 100" the query is rendered with "95" as the value, but taht of course, is not the value I want. How do I get Django to interpret the value as a float -- i.e. teh correct value I'm going for? -
formset factory depending select using AJAX
I want a select depending on anothr select in formset factory but the AJAX asynchronos request work only on the first formset evry time user add university i want dynamicly add etablishment (not all etablishment but only that belong to selected university. here is my code models.py class universite (models.Model): gouvernorat= models.CharField(max_length=250) universite = models.CharField(max_length=250) class Meta: unique_together = ('gouvernorat', 'universite') def __str__(self): return self.universite class etablissement(models.Model): etablissement = models.CharField(max_length=250) univ = models.ForeignKey(universite,related_name='etab_universites') def __str__(self): return "{} de l'université {}".format(self.etablissement,self.univ) class session(models.Model): annee_session = models.CharField(max_length=4) active= models.BooleanField(default=True) def __str__(self): return self.annee_session class choix(models.Model): demandeur = models.ForeignKey(Profile, related_name='profile_choice') session = models.ForeignKey(session, related_name='session_choice') universite_demande = models.CharField(max_length=250) etablissement_demande = models.CharField(max_length=250) class Meta: unique_together = ('demandeur', 'session','etablissement_demande') def __str__(self): return '{} pour session {} choix {}'.format(self.demandeur.user.username,self.session.annee_session,self.etablissement_demande.etablissement) forms.py class univForm(forms.Form): universite = forms.ModelChoiceField(label='Choix de la university', queryset=universite.objects.all().distinct(),required=True) class BaseLinkFormSet(BaseFormSet): def clean(self): if any(self.errors): return universites = [] etablissements = [] duplicates = False for form in self.forms: if form.cleaned_data: universite = form.cleaned_data['universite'] etablissement= form.cleaned_data['etablissement'] if universite and etablissement: if etablissement in etablissements: duplicates = True etablissements.append(etablissement) if duplicates: raise forms.ValidationError( 'Veuillez ne pas répeter les établissements choisis.', code='duplicate_etablissements' ) if universite and not etablissement: raise forms.ValidationError( 'Vous devez choisir pour chaque université un établissement.', code='missing_etablissement' … -
How to handle user pasting a text with bold,italic styling and table in a django text area?
I am trying to design a webpage where users can copy paste their word document contents ,but when I try to copy paste to my django textarea, The effect of bold,italic etc. are missing and table structure is also missing None of the fields available in django model seems to work Models.py from django.db import models class UserForm(models.Model): Body_content=models.TextField(null=True,blank=True) Expecting to copy paste directly from word document to text area without losing basic styling and table. -
How to access related_name in manytomanyfield
I made a follower system in django and want to access the related_name characteristic in the html. the code is as follows models.py class Following(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) users_ifollow=models.ManyToManyField(User, related_name='followed_by',blank=True, null=True) people_followme=models.ManyToManyField(User, related_name='peeps',blank=True, null=True) def __str__(self): return f'{self.user.username} following' views.py class UserFollowView(View): def get(self, request, username, *args, **kwargs): toggle_user=get_object_or_404(User,username__iexact=username) if request.user.is_authenticated: user_profile, created=Following.objects.get_or_create(user=request.user) if Following.objects.filter(user=request.user, users_ifollow=toggle_user).exists(): request.user.following.users_ifollow.remove(toggle_user) else: request.user.following.users_ifollow.add(toggle_user) return HttpResponseRedirect(Following.redirect_route(username)) I want to access the number of people who follow a user through the related_name how can I do that? in the HTML -
Using two different email fo sending eemail in Django
I want to use two email, one for verifying the email and other for sending normal informative emails. I am able to send email for verification with the following code and I want to use my another email for that second perpose. views.py current_site = get_current_site(request) subject = 'Welcome to MySite! Confirm Your email.' htmly = get_template('account_activation_email.html') d = { 'user': user, 'domain':current_site.domain, 'uemail':urlsafe_base64_encode(force_bytes(user.email)), 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user)} text_content = "" html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, text_content, '', [user.email]) msg.attach_alternative(html_content, "text/html") try: msg.send() except BadHeaderError: print("Error while sending email!") user.save() and in settings: EMAIL_USE_TLS = True EMAIL_HOST = config('EMAIL_HOST') EMAIL_HOST_USER = verify@mysite.com EMAIL_HOST_PASSWORD = 'randompass' EMAIL_PORT = config('EMAIL_PORT') DEFAULT_FROM_EMAIL = 'MySte Verification <verify@mysite.com>' Please help!!! -
Djangp-herald: Can't send mails with attachments
Anyone using Django herald for sending notifications? I've been struggling for days to make it work but the lack of documentation and silent failures made it impossible to debug the issues. It seems that the mails are not being sent if I include an attachment in it. from herald.base import EmailNotification def sendMail(): SendThisMail(user, my_modal).send(user=my_user) # creates an error on this line as the file object is closed and inaccessible. @registry.register_decorator() class SendThisMail(SomeBaseClass, EmailNotification): def __init__(self, user, my_modal: models.MyModal): super().__init__(user, my_modal) self.subject = "abc" file = open('.staticfiles/assets/some.pdf', 'rb') self.attachments = [('attachment_1', File(file))] self.context = { **self.context, 'subject': self.subject, 'attachment': self.attachments, } self.to_emails = [user.email] What's wrong with it?