Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HOW CAN I FILTER USERS IN DJANGO MANY TO MANY FIELDS?
HERE IS MY MODEL: class Course(models.Model): title = models.CharField(max_length=100) students = models.ManyToManyField(User,related_name="students") crated_at = models.DateField(auto_created=True) How can I filter all the users in a course? -
Django: Celery worker in production, Ubuntu 18+
I'm learning Celery and I'd like to ask: Which is the absolute simplest way to get Celery to automatically run when Django starts in Ubuntu?. Now I manually start celery -A {prj name} worker -l INFO via the terminal. Can I make any type of configuration so Celery catches the changes in tasks.py code without the need to restart Celery? Now I ctrl+c and type celery -A {prj name} worker -l INFO every time I change something in the tasks.py code. I can foresee a problem in such approach in production if I can get Celery start automatically ==> need to restart Ubuntu instead?. (setup: VPS, Django, Ubuntu 18.10 (no docker), no external resources, using Redis (that starts automatically) I am aware it is a similar question to Django-Celery in production and How to ... but still it is a bit unclear as it refers to amazon and also using shell scripts, crontabs. It seems a bit peculiar that these things wouldn't work out of the box. I give benefit to the doubt that I have misunderstood the setup of Celery. -
How do I change the local path of a language in Django?
Django by default has the English local path defined as /en, If possible I want the language to be 'en' but the url to be myurl.com/us, how would you recommend me to make this change? I have a web set up with 3 languages (['es', 'en', 'it']) in Angular that works with the Django server. The structure is the following: -apps --webapp ---templates ----webapp -----en (inside index.html) -----es (inside index.html) -----it (inside index.html) -conf --settings.py -middleware --locale.py conf.settings.py have this language configuration LANGUAGES = ( ('es', _('Spanish')), ('it', _('Italian')), ('en', _('English')), ) LANGUAGE_CODE = 'es' LANGUAGE_CODES = [language[0] for language in LANGUAGES] Additionally I have configured a middleware to recognize the user's location and place the corresponding language code in the URL from django.conf import settings from .utils.geolocation import get_language_by_ip cookie_name = settings.LANGUAGE_COOKIE_NAME class LocalizationMiddleware(object): def get_language_cookie(self, request): return request.COOKIES.get(cookie_name) def set_language_cookie(self, request, value): request.COOKIES[cookie_name] = value def get_i18n_url_language(self, request): url = request.path.split('/') if len(url) > 1 and len(url[1].split('-')[0]) == 2: return url[1] return None def process_request(self, request): language = self.get_i18n_url_language(request) if language is not None and language not in settings.LANGUAGE_CODES: return if language is None: language = self.get_language_cookie(request) if language is None: language = get_language_by_ip(request) if language is None: … -
Django skips broken template's pats
I'm using Django==1.11.17, python 3.5 When template has error, for example invalid tag, locally django throws exception and returns response with 500 status code. But I found that in production django do not throws exceptions, it just skip broken template part. This makes debug a little bit tricky. Could someone explain why django skips broken templates? Is it possible make production environment throw exceptions instead of ignoring errors? -
Problem in adding releated field to serializer
I have two classes which are Land and UTMPoint: class UTMPoint(models.Model): x = models.CharField(max_length=20) y = models.CharField(max_length=20) z = models.CharField(max_length=20) land = models.ForeignKey('Land', on_delete=models.DO_NOTHING) And their serializers are: class UTMPointsSerializer(serializers.ModelSerializer): class Meta: model = UTMPoint fields = ('id', 'x', 'y', 'z', 'land',) read_only_fields = ('id',) class LandSerializer(serializers.ModelSerializer): user = UserSerializer() utm_points = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Land fields = ('id', 'user', 'activity_field','activity_location', 'area', 'part', 'location','verification_code', 'verified', 'description', 'approved', 'receipt_bank_name', 'receipt_serial', 'receipt_date', 'receipt_amount','utm_points',) read_only_fields = ('id', 'approved',) def create(self, validated_data): user = validated_data.pop('user') user = User.objects.create(**user) user.save() land = Land.objects.create(user=user,**validated_data) land.save() return land As you see Land has utm_points releated field but when I run this test: def test_create_land(self): """test creating land""" payload = { 'activity_field': 'farming', 'user': {'national_code': '12333', 'password': 'passW@rd'}, 'activity_location': 'Kermanshah', 'area': 'sw', 'part': 'sp', 'location': 'the old address', 'verification_code': '1', 'verified': '0', 'description': 'sb is calling for it', 'approved': True, 'receipt_bank_name': 'meili', 'receipt_serial': '12312', 'receipt_amount': '10000', } res = self.client.post(LAND_URL, payload, format='json') self.assertEqual(res.status_code, status.HTTP_201_CREATED) I get this error AttributeError: 'Land' object has no attribute 'utm_points' I have no idea why this error is throwing Land has properly the related field utm_points so why it happes? -
safe, force_escape, etc. What is the exact django template escaping algorithm?
So in the documentation of Django 3.1 template builtins, I've found the following escape-related built-in filters: force_escape escape safe safeseq As well as the following escape-realted tag(s): autoescape (on|off) safeseq especially catches my attention and makes me wonder what exactly the django template escaping algorithm is; among others, how does it interact with custom filters. Indeed, the documentation gives this example: {{ some_list|safeseq|join:", " }} With the following explanation: You couldn’t use the safe filter directly in this case, as it would first convert the variable into a string, rather than working with the individual elements of the sequence. What I'm looking for is: A graphic (draw.io?plantuml?dia?) which explains the steps the data goes through in the simplest case: {{ data }}, depending on the Python type of the variable. A similar graphic which explains more complex cases such as {{ data | myfilterfunction }}, again, taking into account the Python type of the input variable and output value of the custom filter. An explanation or a graphic of how {{s|escape|safe}} is different from both {{s}} of {{s|safe}} in normal auto-escaping context (if it is). Supplementary explanations of how force_escape, escape, safe, safeseq and autoescape work and interact with one … -
django.db.utils.OperationalError: attempt to write a readonly database
I'm using docker + nginx + uwsgi + django. Trying to deploy firstly in my laptop. When i'm run my web application using django server everything ok, also it looks ok when i'm trying start web app with docker without nginx, but when i'm using nginx proxy have a problem with writing data to DB (login/logout user sessions) Problem with rights of my default database issue picture app_1 | Internal Server Error: /logout/ app_1 | Traceback (most recent call last): app_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute app_1 | return self.cursor.execute(sql, params) app_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute app_1 | return Database.Cursor.execute(self, query, params) app_1 | sqlite3.OperationalError: attempt to write a readonly database (venv) yhobby@hp-probook-450-g5:~/PycharmProjects/web_naas$ ls -la total 52 drwxrwsrwx 8 www-data yhobby 4096 Nov 19 15:16 . drwsrwsrwt 9 yhobby yhobby 4096 Nov 18 16:09 .. drwxrwsrwx 6 www-data yhobby 4096 Nov 19 13:59 app -rwxrwxrwx 1 yhobby yhobby 293 Nov 19 14:51 docker-compose-deploy.yml -rwxrwxrwx 1 yhobby yhobby 202 Nov 19 11:35 docker-compose.yml -rwxrwxrwx 1 yhobby yhobby 701 Nov 19 15:16 Dockerfile drwxrwsr-x 8 yhobby yhobby 4096 Nov 19 09:06 .git -rw-rw-r-- 1 yhobby yhobby 100 Nov 19 08:40 .gitignore drwxrwsr-x 3 yhobby yhobby 4096 Nov … -
(index):1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
i am new in django and i am work on ecommerce project. when i try to fetch data i have error (( Uncaught syntax error )) and in terminal in server i have error (( Not Found: /update_item/ )) this is my function.js :: function updateUserOrder(productId, action){ console.log('User Is Logged In, sending data..') var url = '/update_item/' fetch(url, { method: 'POST', headers: { 'Content-Type' : 'application/json', 'X-CSRFToken' : csrftoken, }, body:JSON.stringify({'productId': productId, 'action' : action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:', data) }) } and this is my main.html :: <script type="text/javascript"> var user = '{{request.user}}' function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); </script> can anyone help me??!! -
Creating user throws TypeError
When trying to createsuperuser django throws: NOTIMPORTANT/.virtualenvs/venv/lib/python3.9/site-packages/django/contrib/auth/password_validation.py", line 26, in get_password_validators klass = import_string(validator['NAME']) TypeError: string indices must be integers All my AUTH_PASSWORD_VALIDATORS in settings.py are commented out. It happend when I migrated my project onto production, no longer in development but I don't want anny password validators. -
How to send a GET request using Django and write the response to the database?
Need to send a POST request with the name of the movie, Django sends a request to an external Api and receives full information and saves the response to the database -
I still cant under stand how to use virualenv or wirtualenvwrapper in vscode
I am currently trying to learn django framework, and I am stuck because of the virtual environment setup in vscode, I know how to create a virtual environment and how to activate it and how to install packages inside of it , but my problem is that I cant know if I am using it correctly , and where it should be, for example : which directory should the virtual environment be at when working on a project , should it be with that project at the same directory or what? and also I do not know how to set it up in vscode , so please guys help me with that and give me step by step how I can set the virtual environment in vscode , and in which directory should it be , I am so confused and blocked at this point. -
django combining two query set and called it to html
I have this queryset in views.py, I am using union to combine the two queryset, how am i combine the two queryset using another models, (INNER JOIN in sql) and called it to the html? please check also the html ive given specially in temperature company = FmCustomerUsers.objects.filter(user=request.user.id) employee = FmCustomerEmployeeSupplier.objects.filter( fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name')) feedback = TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords.objects.filter( fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name')).filter( fmCustomerEmployeeSupplierID__in=employee.values_list('id')).union(TrCustomerEmployeeSupplierSubmittedRecords.objects.filter( fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name'))).filter( fmCustomerEmployeeSupplierID__in=employee.values_list('id')) this is my models.py class FmCustomerEmployeeSupplier(models.Model): fmCustomerID = models.ForeignKey('FmCustomer', related_name='+', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Customer") fmCustomerLocationID = models.ForeignKey('FmCustomerLocation', related_name='+', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="CustomerLocation") dateSubmitted = models.DateField(auto_now_add=True, null=True, blank=True) lastname = models.CharField(max_length=500, blank=True, null=True) firstname = models.CharField(max_length=500, blank=True, null=True) middleInitial = models.CharField(max_length=500, blank=True, null=True) bodyTemperature = models.FloatField() fmCustomerSectionID = models.ForeignKey('FmCustomerSection', related_name='+', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="CustomerSection") contact_number = models.CharField(max_length=500, blank=True, null=True) employee_number = models.CharField(max_length=500, blank=True, null=True) address = models.CharField(max_length=500, blank=True, null=True) email = models.CharField(max_length=500, blank=True, null=True) class TrCustomerEmployeeSupplierSubmittedRecords(models.Model): fmCustomerID = models.ForeignKey('FmCustomer', related_name='+', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Customer") fmCustomerLocationID = models.ForeignKey('FmCustomerLocation', related_name='+', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="CustomerLocation") dateSubmitted = models.DateField(null=True, blank=True) firstname = models.CharField(max_length=500, blank=True) middleInitial = models.CharField(max_length=500, blank=True) lastname = models.CharField(max_length=500, blank=True) bodyTemperature = models.FloatField() fmCustomerSectionID = models.ForeignKey('FmCustomerSection', related_name='+', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="CustomerSection") employee_number = models.CharField(max_length=500, blank=True, null=True) contactNumber = models.CharField(max_length=500, blank=True, null=True) address = models.CharField(max_length=500, blank=True, null=True) email = models.CharField(max_length=500, blank=True, null=True) class TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords(models.Model): fmCustomerEmployeeSupplierID … -
Mutual certificate authentication in Azure Web Application
I have a Django application in a Docker that is published in an Azure Web Application (Linux). For some particular API paths that are a gateway backend, I need to setup certificate authentication. For now, I have the web application settings "Incoming client certificates" in mode "Allow" because I need some path to be available without certificate. My application automatically check the certificates if there is a need to so no problems here it works well. My problem is the following, whenever some persons go the frontend I have in the same application that are situated in https://DNS.com/, they are systematically asked on the browser if they want to provide a certificate. The azure web application option provide an option for a whitelist of path, but I don't want to put all my frontend path in the whitelist (because they will be a path that will not be in it). I would prefer an option to ask certificate only at certains URL like for example https://DNS.com/api/gateways/ . My questions are: Is there a way to do that in Azure Web App ? If I put the "Incoming client certificates" to Ignore, will the certificate be checked by the Azure frontend … -
How to send a task to Celery without waiting?
I have the following code in my tasks.py file: @app.task(bind=True) def create_car(self, car): if car is None: return False status = subprocess.run(["<some_command_to_run>"]) return True It should run the command <some_command_to_run> but for some reason the website waits it to finish. I thought the whole point of Celery that it will be run in the background and return status. How can I submit this task in asynchronous way? The wanted behaviour: user asked to create a new car instance, it will add a task to the queue and return true that indicating that the car was requested correctly. In the background it will run that command and return (somewhere - not sure yet where) that status. How to do it? -
i use command location.reload() but its not working
im still new to django and i was trying to make my cart icon to have numbers that show how many items. when i press the add button its didnt work and i must to self reload before see the numbers + or -. can someone found the mistake and write in comment, that will really help me . function updateUserOrder(productId, action) { console.log('User is logged in, sending data...') var url = '/update_item/' fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ 'productId': productId, 'action': action }) }) .then(response => response.json()) .then((data) => { console.log('data:', data) location.reload() }) } -
ERROR: Your view return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view
I am working on a Django Project where i add an event to the database and then send an email to all the subscribers after adding event. I want to do the sending email task async, i followed some blog post and come up with this. from asgiref.sync import sync_to_async import asyncio This is the add event view @login_required(login_url='/login/') async def add_event_view(request): if request.method == 'POST': title = request.POST.get('title') description = request.POST.get('editor') menu = request.POST.get('menu') tags = request.POST.get('tags') banner = request.FILES.get('banner') data = request.FILES.get('data', None) organised_by = request.POST.get('organised_by', None) sponsored_by = request.POST.get('sponsored_by', None) event_date = request.POST.get('event_date', None) uploaded_at = request.POST.get('uploaded_at') Event.objects.create(user_id=request.user, event_title=title, event_description=description, event_category=menu, event_tags=tags, event_banner=banner, event_data=data, organised_by=organised_by, sponsored_by=sponsored_by, event_date=event_date, uploaded_at=uploaded_at) await sync_to_async(send_email(title)) return redirect(etab_view) This is the email sending function async def send_email(title): event = Event.objects.get(event_title=title) content = render_to_string("email.html", {'et': event}) subs = Subscriber.objects.values_list('email_address', flat=True) email = EmailMultiAlternatives('Emagazine Update', content, settings.EMAIL_HOST_USER, list(subs)) email.attach_alternative(content, "text/html") email.fail_silenty = False email.send() I am getting the following error: The view EMAG_APP.views.add_event_view didn't return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view. Can anyone help me out? -
how can in render specific column of uploaded excel file?
by this HTML code, the users can upload files. {% block content %} <form method="post" enctype="multipart/form-data"> <input type="file" id="files" name="files" multiple="multiple" /> <p class="container" style="margin-top: 10px"> <input type="submit" value="upload" class="btn btn-primary" /> </p> </form> {% endblock%} and in the views.py I am trying to get the uploaded file. views.py: def MyView(request): if method == "POST": file = request.FILES.get('files', False) #get the file if file: with open('uploads/files/'+file.name, 'wb+') as destination: #create file path for line in file.chunks(): destination.write(line) #save file data else: return render(request, 'template.html') how can I extract the specific column of uploaded excel and render it to another template? and i want to delete the uploaded file after 1 day. -
How should I add WSGIPython path in VirtualHost for Windows server?
I am trying to add WSGIPythonPath in VirtualHost but it's throwing me an error: Syntax error on line 549 of /etc/httpd/conf/httpd.conf: WSGIPythonPath cannot occur within section I tried to resolve it by following: Where should WSGIPythonPath point in my virtualenv? But, on researching more, I found that WSGIDaemonProcess and WSGIProcessGroup are not supported on Windows according to Why WSGIDaemonProcess isn't available on Windows?. So, How should I add WSGIPythonPath and where so that I can host multiple Django site on my Apache24 server. Any help would be beneficial. Here is my httpd.conf file: LoadFile "c:/python37/python37.dll" LoadModule wsgi_module "c:/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/python37" WSGIPythonPath "E:/edukon/" Listen 7020 <VirtualHost *:7020> ServerName 000.000.000.000 # Django Project WSGIScriptAlias / "E:/edukon/edukon/wsgi.py" <Directory "E:/edukon/edukon"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "E:/edukon/static/" <Directory "E:/edukon/static/"> Require all granted </Directory> Alias /media "E:/edukon/media/" <Directory "E:/edukon/media/"> Require all granted </Directory> </VirtualHost> -
Django ForeignKeyField assign one field with only one another field
I'm trying to create model TravelAgentDocumentType which consists of two ForeignKey's i.e travel_agent and document_type the plan is to have one travel agent can have only one document type, below is my models class TravelAgentDocument(BaseModel): travel_agent = models.ForeignKey(TravelAgent, null=True, on_delete=models.CASCADE) document_type = models.ForeignKey( DocumentType, on_delete=models.SET_NULL, null=True ) TravelAgent model is class TravelAgent(BaseModel): name = models.CharField( max_length=100, unique=True, validators=[validate_travel_agent_name] ) office_location = models.CharField( max_length=100, validators=[validate_location], ) office_land_line_number = LandLineNumberField(blank=True) slug = models.SlugField( unique=True, blank=True) office_phone_number = PhoneNumberField(unique=True) and DocumentType model is class DocumentType(BaseModel): name = models.CharField( max_length=20, unique=True, validators=[validate_document_name] ) how can I assign one travel agent with only one document type? -
Django keeps adding "app" to MEDIA_URL in heroku even though DEBUG = True
This is a new error which was never present before when I had the app running on Heroku. However I am now using the Heroku Postgres SQL so that might causing the issue. Anyways, I have my MEDIA_URL and MEDIA_ROOT set as such STATIC_ROOT = os.path.join(BASE_DIR, "portfoliosite", "staticfiles") STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "portfoliosite", "static"), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') THis works fine on my local server. However in production mode, Django keeps adding "app/" to the start of MEDIA_URL. Does anyone know what could be happening here? Here is the 404 error Request Method: GET Request URL: https://www.remosingh.ca/media/images/newlogo_1_TlcOlPh.png Raised by: django.views.static.serve “/app/media/images/newlogo_1_TlcOlPh.png” does not exist -
'Package' object has no attribute 'reviews'
I am trying to build a list api where comments of the blog post are shown on same api but it generates following error. Got AttributeError when attempting to get a value for field reviews on serializer PackageDetailSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Package instance. Original exception text was: 'Package' object has no attribute 'reviews'. My models: class Package(models.Model): destination = models.ForeignKey(Destination, on_delete=models.CASCADE) package_name = models.CharField(max_length=255) featured = models.BooleanField(default=False) price = models.IntegerField() duration = models.IntegerField(default=5) discount = models.CharField(max_length=255, default="15% OFF") discounted_price = models.IntegerField(default=230) savings = models.IntegerField(default=230) special_discount = models.BooleanField(default=False) rating = models.IntegerField(choices=((1, 1), (2, 2), (3, 3), (4, 4), (5, 5)) ) image = models.ImageField(blank=True) thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) content =RichTextField() highlights = RichTextField() itinerary = RichTextField() image_1= models.ImageField(blank=True,null = True) image_2= models.ImageField(blank=True,null = True) image_3= models.ImageField(blank=True,null = True) date_created = models.DateField() def __str__(self): return self.package_name # def is_featured(self): # return self.featured class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) package = models.ForeignKey(Package, on_delete=models.CASCADE, related_name='review') full_name = models.CharField(max_length=255) review = RichTextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name class Meta: ordering = ('created_at',) My view: class AllPackageDetailAPIView(RetrieveAPIView): queryset = Package.objects.all() serializer_class = PackageDetailSerializer My serializers: class ReviewSerializer(serializers.ModelSerializer): … -
Connect web framework to Azure Analysis Services
This is not a code question, more of suggestion type one. I am also new at this so keep your torches away. My company wants to create something more flexible then using BI tools like Tableau for our front-end, so we want to build our own web app. So my question here is which web framework would be good to use to connect to Azure Analysis service for data as we still want to keep our data models? I am currently looking into Django because, as I read, speed and security (which is really important) and I am familiar with Python, but is this way to go? Or something not Python based. -
I am trying to pass row value between 2 tables but somehow last jquery onclick is not working at all. What am i missing?
With this i was able to pass row value from one to other and hide the row i clicked $('.js-report-delete').unbind('click').click(function() { var report_num = $(this).closest('tr').find('.report_no').text(); var row = '<tr style = "background-color : #ed962b;"><td class="report_no">'+ report_num +'</td></tr>'; $('#report_delete').append(row); $(this).closest('tr').hide(); }); And after that i am trying undo it, when i click the row that recently added on the other table which will remove that row and unhide original row from the first table but somehow this query not working at all. What am i missing? $('#report_delete tr').not('thead tr').on('click',function() { var report_num = $(this).closest('tr').find('.report_no').text(); $(this).closest('tr').remove(); $('#report_out tr').not('thead tr').each(function() { if($(this).closest('tr').find('.report_no').text() == report_num) { $(this).closest('tr').show(); } }); }); -
Django Aws Ses email send issue b'Invalid MAIL FROM address provided'
In my settings.py i have a mail congiguration Like : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.getenv('EMAIL_HOST') EMAIL_PORT = os.getenv('EMAIL_PORT') //465 EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') EMAIL_USE_TLS = os.getenv('EMAIL_USE_TLS') And in my code i am using like : connection = get_connection( host=settings.EMAIL_HOST, port=settings.EMAIL_PORT, username=settings.EMAIL_HOST_USER, password=settings.EMAIL_HOST_PASSWORD, use_tls=settings.EMAIL_USE_TLS, ) print('11111111') print(connection) print('222222222') mail = send_mail('diditwork?', 'test message', settings.EMAIL_HOST_USER, [userObj.email], connection=connection) But in Result i am getting the error Like : File "/var/www/html/gelmeko/myenv/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 125, in _send self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) File "/usr/lib/python3.6/smtplib.py", line 867, in sendmail raise SMTPSenderRefused(code, resp, from_addr) smtplib.SMTPSenderRefused: (501, b'Invalid MAIL FROM address provided', 'AKI**************') Can any one please help me related this ?? what i am doing wrong here i am sending the mail through AWS SES credentials. -
Crontab in django uploads last 10 every 3minutes
In my views, I have this to upload a table with a list of the last 10 Model.objects.all().order_by('-id)[:10] I'm trying to make a cronjob, so at every 3minutes, it adds 1 to the top and removes the last one, so to make the list continue to be 10