Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter date According to Today Current Date in Django?
I am trying to filter date in Django according to current date, But it's displaying mr 0 results, Please let me know Where I am mistaking. Hers is my models.py file... class Customer(models.Model): name = models.CharField(null=True, blannk=True) customer_date = models.DateTimeField(null=True, blannk=True) here is my views.py file, where i am trying to get date according to today date... from datetime import datetime, timedelta, time, date def getdate(request): today=datetime.today() customer_data = Customer.objects.filter(customer_date=today).count() print(customer_data, "Count Values") -
How to send email in django with attaching dynamic context passed invite.ics file?
My is a simple celery asyncronus task which sends email attaching invite.ics file, but i dont know how to pass dynamic context in invite.ics file? my task file for sending email -> import os from django.conf import settings from celery import shared_task from time import sleep from django.core.mail import send_mail from django.core.mail import EmailMessage @shared_task def send_email_with_celery(company, date, sender, receiver): email = EmailMessage(f'Interview with {company}', f'You have been selected for the interview at time {date}', f"{sender} from {company}", [f'{receiver}']) email.attach_file('invite.ics', 'text/calendar') email.send() return None my invite.ics file--> BEGIN:VCALENDAR VERSION:2.0 PRODID:-//hacksw/handcal//NONSGML v1.0//EN BEGIN:VEVENT UID:{{ sender }} <-- dynamic sender context DTSTAMP:19970714T170000Z ORGANIZER;CN=Sonu Sud:MAILTO:{{ receiver }} <-- dynamic reciever context DTSTART:20201005T110000Z <-- should be dynamic time value in this format DTEND:20201005T114500Z <-- should be dynamic time value in this format SUMMARY:Interview with {{ company }} <-- should be dynamic Company name GEO:48.85299;2.36885 END:VEVENT END:VCALENDAR i want to pass the context like this -> context = { "sender":, "receiver":, "start":, "end":, "company": } how to pass the context in invite.ics file...? -
Django Class-based view pass custom request
I am using unittest in my project, and the following is my test code. import unittest from unittest.mock import patch, Mock from lists.views import NewListView @patch('lists.views.NewListForm') class NewListViewUnitTest(unittest.TestCase): def setUp(self): self.request = HttpRequest() self.request.POST['text'] = 'new list item' self.request.user = Mock() def test_passes_POST_data_to_NewListForm(self, mockNewListForm): NewListView(self.request) # The important bit mockNewListForm.assert_called_once_with(data=self.request.POST) I want to pass a custom request, which as you see has some POST data. I had originally had a view, so I could pass a custom request. Now, with a class based view, how can I do that? I am currently getting an error which says: TypeError: __init__() takes 1 positional argument but 2 were given I did try NewListView.as_view(self.request), but that says TypeError: as_view() takes 1 positional argument but 2 were given I know you should use the Django test client and make POST requests using the URL, not calling the actual view, but this is how they did it in the book I am currently studying (Test-Driven Development with Python by Harry Percival. Unfortunately, he doesn't seem to have updated his appendices, where he teaches the class based view stuff, so I am doing it my self. Or trying to.) Thanks. -
How to create one migration file for one model file in django
In a django app i created models folder, in which folder contains multiple model files, When i run command python manange.py makemigrations <app_name>, it generates one migration file for all the *.py models. So, is this possible to generate multiple migration files for multiple *.py models. -
How to send from JS to Python Django Server Backend
I have started learning about Javascript and I am trying to include it to my Django Project to calculate the time users are on the page so I found the answer to this question HERE but I am unable to implement it as it is the first time for me to link between JS and Django Python backend. Here is what I understand: Step 1 Add the following script for all HTML templates: <script src="timeme.js"></script> <script type="text/javascript"> TimeMe.setIdleDurationInSeconds(15); TimeMe.setCurrentPageName("my-home-page"); TimeMe.initialize(); window.onload = function(){ setInterval(function(){ var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds(); document.getElementById('timeInSeconds').textContent = timeSpentOnPage.toFixed(2); }, 25); } </script> Step 2 I am not sure exactly to place the below code to send the data to the backend to be read in Django Admin to know which user has been spending on each page xmlhttp=new XMLHttpRequest(); xmlhttp.open("POST","ENTER_URL_HERE",true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds(); xmlhttp.send(timeSpentOnPage); My questions are: Where should I place the 2nd Code? Should I start a new app in my django project to read the file sent from the JS? What is the TimeMe.setCurrentPageName("my-home-page"); what variable should I add? is it the HTML name of the name in the URL? -
Superuser dumpdata/loaddata in Django
I'm having a trouble on how can I dump a encrypted password data into authuser table in django, Currently I'm using python manage.py loaddata fixtures.json to dumpdata into database it works fine but the password is not encrypted, how can I encrypt it when using loaddata?. Is there any expert can share solutions or ideas with this problem, Much appreciate! [{"model":"auth.user", "pk" : 2, "fields" : {"password" : "superadmin", "is_superuser" : "1", "username" : "superadmin", "first_name" : "name" , "last_name" : "lname" , "email" : "a@gmail.com" , "is_staff" : "1", "is_active" : "1" }] -
Weird Concatenated Strings in browser URL
I am learning Django with materials in which the tutor used an old version of Django. I have been able to transform some of the codes into the currently supported version with the aid of some other recent material and by browsing through related questions here. The problem I have now is though everything works but the browser URL will display some weird strings concatenated together with the slug. Kindly help me point out what modifications I need to make on the following codes. Thanks in advance. This is the corresponding error part of the browser URL: (%3FP2020%5Cd%7B4%7D)/(%3FP11%5Cd%7B2%7D)/(%3FP03%5Cd%7B2%7D)/(%3FPsecond-post%5B-%5Cw%5D+) This is the method in the models.py: def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) These are the codes in the urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.post_list, name='post_list'), path('(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/', views.post_detail, name='post_detail'), ] These are the codes in views.py from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request, category=None): posts = Post.published.all() return render(request, 'list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'detail.html', {'post': post}) -
Guys I can't use my heroku domain name to generate a new Facebook access_token using postman like I used to do with my localhost
I did all steps mentioned here https://github.com/RealmTeam/django-rest-framework-social-oauth2 using POSTMAN to generate an access_token to login to Facebook using localhost:8000 and it generated perfectly and I got the the access_token and I can login perfectly but when I test the same way with a different url of my new domain name I can't get an access_token and I got an error said no module named 'social' so what should I do to do login with Facebook and generate access_token after pushed my project to heroku !!? There are all the steps I did after pushed my project to heroku : I Changed My Site Url Of My App On Facebook from localhost:8000 to https://whispering-hamlet-67095.herokuapp.com/ changed my ALLOWED_HOSTS In Settings.py To ALLOWED_HOSTS = ["localhost","whispering-hamlet- 67095.herokuapp.com"] This Step=> ### Testing On PostMan To Get facebook access_token As Usual Like I Used To Do When My Project is Only Running Locally But I Got This error When I Changed The Url From localhost:8000/ to https://whispering-hamlet-67095.herokuapp.com/ and my code of urls.py: from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views from django.conf.urls.static import static from django.conf import settings from egystoreapp import views, apis urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', … -
Need currency format from a number in template
I am not a Django programmer but trying to look at how I can change the output of number which is supposed to printed to the page as USD. For example: It prints "Price: 3295000" when I would like it to say "Price: $3,295,000". This is the template part: <h5 class="card-title h5-size">Price: {{property.price}}</h5> What code can I put in the template to output this in the way that I'm looking for? -
How to check the file type of python InMemoryUploadedFile file?
I am creating an app using python Django to merge documents and I would want to check the file type of the uploaded files because the code can only merge pdf file. I have tried to use endswith and split function to check the file type but there was error saying InMemoryUploadedFile has no such attributes. Hence, are there any other methods to check for file type of InMemoryUploadedFile file ? My code is shown below: I want to make sure that check that if the uploaded files are not pdf files, the code will ignore it (adding if statement & continue) def mergedocument(request): doc = request.FILES.getlist("file[]") mergedoc =[] for docu in doc: fs = FileSystemStorage() file_path = fs.save(docu.name, docu) pdoc = documentsfile(docs=file_path) pdoc.save() mergedoc.append(docu) merger = PdfFileMerger() for pdf in mergedoc: merger.append(pdf) merger.write("C:\\Users\\Downloads\\Merged.pdf") merger.close() messages.info(request,a) messages.info(request,'Files merged and stored in your Downloads folder') return redirect('home') -
POST request to localhost using Python requests
I have my Django website running on my local server at port 8000. From a separate python file, I want to send a post request triggering one endpoint of my website. But unable to do that even after adding all the required info. Please help!! import requests URL = 'http://127.0.0.1:8000/api/org/create/' client = requests.Session() client.get(URL) csrftoken = client.cookies['csrftoken'] data = dict(csrfmiddlewaretoken=csrftoken) headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'} response = client.post(URL, data=data,cookies=client.cookies, headers=headers) print(response.status_code) It is giving me this error. EC:\Program Files\Python37\lib\unittest\case.py:643: ResourceWarning: unclosed <socket.socket fd=420, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 10510), raddr=('127.0.0 .1', 8000)> outcome.errors.clear() ====================================================================== ERROR: test_org_create (test_org.TestOrg) ---------------------------------------------------------------------- Traceback (most recent call last): File "\test_org.py", line 13, in test_org_create csrftoken = client.cookies['csrftoken'] File "\venv\lib\site-packages\requests\cookies.py", line 328, in __getitem__ return self._find_no_duplicates(name) File "\venv\lib\site-packages\requests\cookies.py", line 399, in _find_no_duplicates raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) KeyError: "name='csrftoken', domain=None, path=None" How to resolve this? Please comment for any other info. -
Django project "module markdown2 isnot found"
when i run python manage.py runserver in my project folder i get an error. like no module markdown2 I put import markdown2 top of my views.py file. Is anything else i need to do? anyone has any idea? thanks Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self.check(display_num_errors=True) File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/senayyakut/wiki/encyclopedia/urls.py", line 3, in <module> from . import views File "/Users/senayyakut/wiki/encyclopedia/views.py", line 1, in <module> import markdown2 ModuleNotFoundError: No module named 'markdown2'``` -
Best way to structure site files before going live
I have built a website using Django and I'm about to go live. I had a question about the structuring of CSS files before I publish. Currently my site looks like this -Root -App 1 -App 1 Files -App 2 -App 2 Files -App 3 -App 3 Files -mysite -Templates -App 1 Templates -App 2 Templates -App 3 Templates -Static -Images -CSS Files -JS My main css was quite large so I split it up into separate css files for each section. I'm wondering if it would make sense to place the css files next to their corresponding templates, or if it would be best to leave them in the static folder as they are now. Thank you! -
django.db.utils.IntegrityError: NOT NULL constraint failed: new__profiles_userprofile.email
How can I fix it , I simple want to add email_address in UserProfile model and it showing me this django.db.utils.IntegrityError: NOT NULL constraint failed: new__profiles_userprofile.email error when i try to migrate. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_address = models.EmailField(max_length=254,default=None,blank=True,null=True) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) close_friends = models.ManyToManyField(User,related_name='my_close_friends', blank=True) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) background =models.ImageField(("Background"), upload_to='backgrounds', default = 'ak.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) -
DRF asking for CSRF Token with TokenAuthentication as the only auth method
My only auth system for DRF is TokenAuthentication and it is still asking for a CSRF Token on a function based view. I'm not having this problem with class based views. settings.py: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication' ] } views.py: @api_view(['POST']) @authentication_classes([TokenAuthentication]) def submit_vote(request): # ... On Postman's POST request: Forbidden (CSRF cookie not set.): /rest/submit_vote/ [04/Nov/2020 02:05:38] "POST /rest/submit_vote/ HTTP/1.1" 403 2864 What?! I don't have any pending migration. -
How to exclude fields from Forms created from Models in Django?
Hello Stack Overflow Community, I am attempting to follow DRY principles and generate a form with a model I defined for tables in the database. Unfortunately it seems that createlistings.html prompts users to fill out Listed by, when it shouldn't be. How do I remove that? Also how can I fix this really ugly formatting or atleast make it not look like spaghetti? Will I need to do it through css or are there some basic defaults through Django? Thanks. Here is my Model definition from models.py: class AuctionListing(models.Model): CATEGORY_CHOICES = [ ... ] listing_title = models.CharField(max_length=64) image = models.ImageField(blank=True) image_url = models.URLField(blank=True) description = models.TextField(max_length=400) category = models.CharField( max_length=6, choices=CATEGORY_CHOICES ) starting_bid = models.DecimalField(max_digits=10, decimal_places=2, default=0) date_posted = models.TimeField(auto_now=True) # When the referenced object (User) is deleted, also delete the # objects (Auction Listings) that have references to it. listed_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="listings") def __str__(self): return f"{self.listing_title} ({self.category})." Here is my form definition in views.py: class CreateListing(ModelForm): class Meta: model = AuctionListing exclude = ('listing_by', 'listings', ) # listed_by is filled out in view Also, for readability is it good practice to import my CATEGORY_CHOICES from a different file if it's a really long list? -
How do i create a static file in django
Please how can I correct this errorenter image description here I keep getting errors connecting BASE_DIRS to my static files -
How to create profile update view without profile create view?
Here I am trying to create profile update view , i haven't use profile create view in my views.py because that i am creating profile by signals so , i dont need profile create view but i need update view so that user can update his profile, i am getting an error ValueError at /profiles/profiles/admin/1/ The view profiles.views.ProfileUpdateView didn't return an HttpResponse object. It returned None instead. i dont know to fix it, here below is my code , If you think i am doing in very unprofessional way than please let me know and tell me the more professional way to do this. views.py class ProfileUpdateView(UpdateView): refirect_field_name ='profiles:final_detail.html' form_class = UserUpdateForm model = UserProfile def get_context_data(self, *args, **kwargs): context = super(ProfileUpdateView, self).get_context_data(*args, **kwargs) update_form = UserUpdateForm(instance = self.request.user) context['form']=update_form return context def form_valid(self,form): form.save() urls.py app_name = 'profiles' urlpatterns = [ path('final/<str:username>/',FinalProfileDetailView.as_view(),name = 'final_detail'), path('profiles/<str:username>/<int:pk>/',ProfileUpdateView.as_view(),name = 'update'), ] model.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) close_friends = models.ManyToManyField(User,related_name='my_close_friends', blank=True) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) background =models.ImageField(("Background"), upload_to='backgrounds', default = 'ak.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) objects = ProfileManager() def __str__(self): return f'{self.user.username}' def save(self,*args, **kwargs): super(UserProfile,self).save(*args, … -
Django manytomany field shows all existing objects of that type in the admin
The title covers most of it. I have a model Game with a manytomany field called users this field has blank=True because it can be empty. Whenever I open this object in the admin it shows a list of all existing users instead of the users that are added to this particular game object. If i print the users in my consumer it shows that it is empty (which it is). How can I make the admin show the user objects that are in the users field. -
Calling properties using "Self" keyword and One-To-Many Relationships in Django
I'm new to Django, and having some trouble understanding how the self keyword works, compared to this in JS or C#. I've been working through the [Django REST API tutorial][1], and now am trying to add a second Model class. I'd like to have a one-to-many relationship between each Snippet and SubSnippets, but would like to have my SubSnippets inherit the language and style properties of the parent Snippet so that I can use them in the formatter for each SubSnippet. Here's the code I've added to models.py: snippet = models.ForeignKey(Snippet, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) owner = models.ForeignKey('auth.User', related_name='sub-snippets', on_delete=models.CASCADE) highlighted = models.TextField() class Meta: ordering = ['snippet', 'created'] def save(self, *args, **kwargs): lexer = get_lexer_by_name(self.snippet.language) linenos = 'table' if self.linenos else False options = {'title': self.title} if self.title else {'snippet title': self.snippet.title} formatter = HtmlFormatter(style=self.snippet.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter)``` The problem is that `self.snippet.language` doesn't seem to be calling the actual Snippet class, because I'm getting an error that says "Instance of ForeignKey has no 'language' member." Same with `self.snippet.title` and `self.snippet.style`. I find the convention of putting all Models in a single file … -
Django Datatables taking too long to load
I am trying to load 25600 rows into datatables but it's taking around 10 seconds. The request is via an ajax API call. views.py @api_view() def get_all_data(request): get_all_data_ = Data.objects.values("name","contact_number","email_address","address","age", "location_type","sector","phase","total_data","total_usage","city","district") return JsonResponse(list(get_all_data_), safe=False) template.html var table = $('#data-table').DataTable({ serverSide: true, "ajax": { "url": "/alldata/", "dataSrc": "" }, "columns": [ {"data": "name"}, {"data": "contact_number"}, {"data": "email_address"}, {"data": "address"}, {"data": "age"}, {"data": "location_type"}, {"data": "sector"}, {"data": "phase"}, {"data": "total_data"}, {"data": "total_usage"}, {"data": "city"}, {"data": "district"} ], }); How can i make it instantaneous? -
Django Template Display Context in Modal On Click
I may be completely going about this wrong, but fairly new to Django Templates and appreciate any help. I have a template that dynamically creates a table of rows of data based on context passed to the template from the view. html table rows being generated by loop <tbody> <!--Table Rows--> {% for ruleset in rulesets %} <tr> <th scope="row">{{ forloop.counter }}</th> <td><a href="{% url 'ruleset_detail' ruleset.id %}">{{ ruleset.ruleset_name }}</a></td> <td>{{ ruleset.ruleset_description }}</td> <td>{{ ruleset.ruleset_create_date|date:'m-d-Y' }}</td> <td style="text-align:center;">10</td> <td style="text-align:center;"> <div> <!-- EDIT modal button--> <button type="button" id="editRuleset" name="{{ ruleset.id }}" value="{{ ruleset.ruleset_name }}" class="btn btn-link align-middle" data-toggle="modal" data-target="#editRuleset"> <i class="fas fa-edit fa-sm"></i> <span style="font-size:small">EDIT</span> </button> </div> </td> </tr> {% endfor %} </tbody> the result is an EDIT button created for each row of data in the table with the rows ruleset id and name stored as the button name and value. When the user clicks on the EDIT button, a modal is displayed that should take the data from that row and assign it to the value of form inputs. modal form <form action="" method="PUT"> {% csrf_token %} <div class="modal-body"> <div class="form-group"> <div class="pt-2"> <label for="edit_ruleset_name">Ruleset Name</label> <input id="edit_ruleset_name" name="edit_ruleset_name" class="form-control" type="text" value="" required> </div> <div class="pt-4"> <label for="edit_ruleset_description">Ruleset … -
Value won't get updated in Calendar form using sessionStorage
I am importing a calendar widget using django. Previously it was working fine if I changed the date and refreshed the page the date automatically save the entered date value. However, when I added a maxdate to the widget on page reload it will only refresh to the maxdate value (today's date) and never get updated. options={ "format": "YYYY-MM-DD", # moment date-time format "calendarWeeks": True, "locale": "en-gb", "maxDate": datetime.datetime.today().strftime('%Y-%m-%d') })) My Solution: I figured I can solve this problem saving the value through sessionStorage and updating the value. My code works as intended but for some reason will not update my widget. My thought is the calendar widget maxdate is overriding my entered date. You can see below my value I inputted and the max date towards the end of the code line. Has anyone encountered this problem? Seems like my max date (today) will override my inputted 2020-09-07 value on page reload. <input type="text" name="Calendar" value="2020-09-07" class="form-control" id="id_Calendar" dp_config="{"id": "dp_65", "picker_type": "DATE", "linked_to": null, "options": {"showClose": true, "showClear": true, "showTodayButton": true, "format": "YYYY-MM-DD", "calendarWeeks": true, "locale": "en-gb", "maxDate": "2020-11-03"}}" My JS to handle sessionStorage $(document).ready(function() { let current_value = document.getElementById("id_Calendar").value; let new_value = sessionStorage.setItem("id_Calendar",current_value); var getItem = sessionStorage.getItem("id_Calendar"); if … -
django render_to_string not cares about python variables that's saved in database model
i have an text email template saved in database , and it is include some python variables , for example {{ company_name }} but when i use 'render_to_string' django function , it see the '{{ company_name }}' as a string not as a python variable , and here is my codes: 1- this the text which is saved in database : "" this is an email auto reply test from {{ company_name }} sales department, we will contact you as soon as possible . thank "" 2- and this is my view codes: email_info_object = Email_Auto_Reply.objects.get(EAR_department=Site_departments.objects.get(DEB_name=department)) email_body = email_info_object.EAR_body company_name = 'company name example ' render_context = { 'email_body':email_body, 'company_name':company_name, } email_body = render_to_string("staff/email_rendering/auto_reply_new_request.html", render_context) print(email_body) 3- and this is my 'staff/email_rendering/auto_reply_new_request.html' file. {% autoescape off %} {{ email_body|safe}} {% endautoescape %} 4- and this is the output of print : 00 8848 [04/Nov/2020 01:17:03] "GET /admin/jsi18n/ HTTP/1.1" 200 3187 [04/Nov/2020 01:17:08] "GET /submit_ticket/ HTTP/1.1" 200 5244 this is an email auto reply test from {{ company_name }} sales department, we will contact you as soon as possible . thank [04/Nov/2020 01:17:13] "POST /submit_ticket/ HTTP/1.1" 302 0 -
VCF file write into amazon S3 bucket django
I need to write(save) a VCard .vcf file to my amazon s3 bucket, but there has been problems. I have managed to save vcf file locally and then duplicate to s3 bucket. How I can store direclty into s3 bucket, btw just started using aws, hope you can help! I get data from my customer model database and this is my django view import ... import boto3 customer = Customer.objects.get(identifier=identifier) data = {} data['n'] = customer.first_name + ' ' + customer.last_name data['fn'] = customer.first_name + ' ' + customer.last_name data['tel'] = customer.phone data['email'] = customer.email vcard = vobject.readOne('\n'.join([f'{k}:{v}' for k, v in data.items()])) vcard.name = 'VCARD' vcard.useBegin = True vcard.prettyPrint() ############# WORKS BUT SAVES LOCALLY ############### # path = (settings.MEDIA_ROOT + 'customer.vcf') # with open(path, 'w', newline='') as f: # myfile = File(f) # myfile.write(vcard.serialize()) ############# WORKS BUT SAVES LOCALLY ############### ############# dublicates to bucket ############### s3 = boto3.resource('s3') BUCKET = "bucket" s3.Bucket(BUCKET).upload_file(path, 'customer.vcf')