teleren/devto huggingface dataset:
About DoesNotExist Exception with Django ForeignKey
Tags: python, django
Published: 2020-09-16 04:50:05

---
title: About DoesNotExist Exception with Django ForeignKey
published: true
description: 
tags: python, Django
//cover_image: https://direct_url_to_image.jpg
---

For a model defined in Django，consider, a foreign key field pointed to User:

```
class Article(Model):
    title = CharField()
    content = TextField()
    user = ForeignKey(to=get_user_model())
```

If `article` is an instance of Article, `article.user` would get a User instance(base on get_user_model()) based on the foreign key defined.


If you happen to a project where the data consistency is not well maintained, e.g., the admin had deleted several old users despite the data dependency. When calling `article.user`, you may get a DoesNotExist error, mostly look like

```
DoesNotExist: User matching query does not exist. 
```

From the source of Django, I found a comment in db/models/fields/related_descriptors.py:

```
# Assuming the database enforces foreign keys, this won't fail.
```

This means when dealing with the consistency of ForeignKey, Django tends to simply raise an error and leave it to the database admin. But in some cases, if we can resolve `article.user` as a None object, it would be easier for the code to handle, or more compatible with other serializers/validators.

I monkey-patched the module with the following code:

```
from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor

def get_object(self, instance):
    qs = self.get_queryset(instance=instance)
    # Assuming the database enforces foreign keys, this won't fail.
    return qs.filter(self.field.get_reverse_related_filter(instance)).first()

ForwardManyToOneDescriptor.get_object = get_object
```


The code replaces `query_set.get` with `query_set.first`, no exceptions raised but return a None when object does not exist. By the way, when if the uniqueness of the foreign key object can be assured, e.g. the foreign key is the primary key in the table related, `query_set.first` is faster than `query_set.get`, since it stops scanning the table on the first row matched.
Number Guessing Game using javaScript
Tags: javascript, html, css, vanillajs
Published: 2020-09-16 04:41:23

Tried to create a simple yet complicated Number Guessing Game using #javascript. Event Delegation is used to target DOM elements. After creating this simple app even I can't win within the first try. Smiling face with tear try it here- https://bit.ly/32wBHRU code-https://codepen.io/isurojit/pen/GRZBdoq #HTML #css #ReactJS #webdev #webdeveloper
LeetCode 977. Squares of a Sorted Array
Tags: algorithms, leetcode, javascript, twopointertechnique
Published: 2020-09-16 04:39:23

###Description:
Given an array of integers `A` sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.

###Example 1:
```
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
```

###Example 2:
```
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
```
###Solution:
Time complexity : O(n)

```javascript
// This solution uses a Two Pointer Technique
// We compare the square of the element at the right pointer
// with the element at the left pointer
// We add the max square value to the output array, 
// then we move that element's pointer closer to 
// the opposite side
// We repeat this process until the pointers are equal
// or one pointer has moved past the other
var sortedSquares = function(A) {
        const output = [];
        // define pointers
        let left = 0;
        let right = A.length - 1;
        // index in output array we will add values
        let i = right;
        while (left <= right) {
            // get squared values
            const leftVal = Math.pow(A[left], 2);
            const rightVal = Math.pow(A[right], 2);
            // compare squared values
            if(leftVal > rightVal) {
                // add element to output[i], then subtract 1 
                // from i
                // move pointer closer to the opposite side
                output[i--] = leftVal;
                left++;
            } else {
                output[i--] = rightVal;
                right--;
            }
        }
        return output;
};
```
Amazon S3 Quick Reference 
Tags: aws, infographics
Published: 2020-09-16 04:37:04


Amazon S3 Quick Reference for Certification, interview and study!

![](https://s3.amazonaws.com/blog-images-rajanpanchal.net/s3-infographics/s3-infographics.png)

*If you like the post, feel free to share and follow me on [Twitter](https://twitter.com/PanchalRajan) for updates!*
about me :)
Published: 2020-09-16 04:28:23

Create a blog post in which you share your skills, best projects, leadership activities and dream job!!!

Hello! My name is Jocelyne and I would describe myself as a team player... I like to think of myself as a person who likes to learn as well. My best projects have been those that I have been able to do for school, such as designing webpages or applications. I was invited to work on a web designing project at Southwest University, which is the university I currently study at. I was invited along side two other students. This project has been lots of fun as it lets us put in action all the things we have been learning in class. This also lets us come across real life problems, and figure out real life solutions. My dream job would be doing anything that will help me grow professionally. I think I would also like to teach others about what I am passionate about!
10 Web Designs in 1 Hour - Design Challenge
Tags: webdev, tutorial, beginners, design
Published: 2020-09-16 04:20:16

**TLDR** I Designed **10 Websites in a single hour** recording the whole thing for YouTube! **Florin Pop** then developed them all!

I was inspired by a recent post by [Florin Pop](https://www.youtube.com/channel/UCeU-1X402kT-JlLdAitxSMA) where he created 10 JavaScript Projects in 10 hours. So we teamed up. Not only that, we decided to make this even more insane by upping the difficulty and doing the whole thing in a single hour.

{% youtube lf_vL-TNOEk %}
<center>[*If you enjoyed this content, hit like, it really helps us creatives promote the content*](https://youtu.be/lf_vL-TNOEk)</center>

The first part will involve me designing 10 websites from different categories in a single hour. This only gives me about 6 minutes per design. The second part will happen on Florins channel where he will develop those 10 designs. 

The real question is, what’s more difficult, the design phase or the development phase! Here is a quick rundown of the types of website designs!

1. Automotive Car Design
2. Restaurant Food Design
3. Shoe Footwear Design
4. Fashion Clothes Design
5. Tourism Landscape Design
6. News Magazine Design
7. Legal Law Firm Design
8. TV Video Streaming Design
9. Technology IT Design
10. Portfolio Resume Design

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/x1b5rgqz3moxu0hwpesh.gif)

**Figma Designs:**
https://www.figma.com/file/QmyHjqAZ49tuncZq1kDhK7/10-Website-Designs-in-1-hour-Design-Challenge?node-id=0%3A1

I don’t always have time to create content, between a full time job, family and live, everyday feels short and fast. This is why I enjoyed this challenge so much. Nothing we do can ever be perfect. We can however focus on getting it done. With this in mind, knowing that it’s possible to both design and develop websites in just an hour or two should make it feel possible for those both overwhelmed or starting out.

I will put the designs on Figma for those who are interested to see, and I am sure that all the code for the 10 websites will also be on github by Florin.

I honestly want to provide more valuable content that is both engaging and interesting for people to watch. It’s hard to figure out what people want to watch, but having challenges and adding pressure is something fun and new to test out.

If you want to know more about me or Florin, I definitely think you should check out our channels, as we are both new and working hard to grow.

## Follow and support me: 
Special thanks if you subscribe to my channel :)
* [🎞️ Youtube](https://www.youtube.com/channel/UCvM5YYWwfLwpcQgbRr68JLQ?sub_confirmation=1)
* [🐦 Twitter](https://twitter.com/adrian_twarog)
Subdomain routing with nuxtJS and k-domains module
Tags: nuxt, npm, routing, subdomains
Published: 2020-09-16 04:03:22

Hello guys, few days ago i was trying to manage subdomains for my site where i wanted to have same layout across all and without repetition of the code. 
{% post https://dev.to/madhusudanbabar/handling-subdomains-with-js-frameworks-3eb8 %} i tried all possible ways from creating own routes to modifying default routes and after a lot of efforts, i finally achieved the result i wanted but i noticed many posts, feature requests on github for the same, so i ended up creating my very first npm [module](https://github.com/madhusudanbabar/k-domains/), Here's the link to the article elaborating the use of the module.
{% medium https://medium.com/@madhusudanbabar/handling-multiple-sub-domains-in-nuxtjs-with-k-domains-module-1c5a039baba1 %} 

Here's the [source code](https://github.com/madhusudanbabar/k-domains/)
And here's the [package 📦](https://www.npmjs.com/package/k-domains)
You are welcome for feedbacks / suggestions
Gaming Review Zone 
Tags: ruby, activerecord, sinatra, flatiron
Published: 2020-09-16 03:54:12

# Built my first web application using Ruby
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/eutxu4ojy2sc8tdelzsi.png)


Gaming Review Zone (GRZ - Pronounced as Gears) is a simple website where you can create reviews about video games. As a gamer, I thought this concept for my first web app would be perfect! 

## The process

To keep it short and simple, `Sinatra` is one of the web frameworks I used along with `ActiveRecord` and `SQLite`. To start my skeleton, I used the `corneal` gem to generate the base of the application with all of my models, views, and controllers. 

I populated the database with my users, reviews, and upvotes table and formed `has_many` and `belongs_to` relationships between them. I implemented authentication/authorization for log in, log out functions and confirming the users identity. I added all of the necessary routes to all 4 controllers (application, reviews, sessions, users) and the necessary html for my views. 

## `.build` Method
The `build` method was something that was confusing to me. After searching high and low for examples, I finally have an idea on what it does.

`build` works the same as `new`, the only difference is `build` instantiates the object's associations while `new` only instantiates the object. For example: 

```
#tux

test = Review.new(game_title: "test", body: "test")

=> #<Review id: nil, user_id: nil, game_title: "test", body: "test", upvotes: nil, created_at: nil, updated_at: nil>
```
Notice how our `user_id` is `nil`

```
@test = test.build_user(email: "test@test.com", username: "testy", password: "12345678")

=> #<User id: nil, email: "test@test.com", username: "testy", password_digest: "$2a$12$9AuPJRVMMaKCiNmHy7YUl.ncgA5YN5Cvj9lFhp/c1ho...">
```
#####**Note:** *I'm using `build_user` since this is a `belongs_to` relationship and not a `has_many` relationship. Using `test.user.build` will give you a `NoMethodError`*

##### *If I do `user.build_review(game_title: "test", body: "test")` I will get an `NoMethodError` as well, but `user.reviews.build(game_title: "test", body: "test")` will work since it's a `has_many` relationship.*
```
@test.save
=> true

@test
#<User id: 17, email: "test@test.com", username: "testy", password_digest: "$2a$12$w9Xx3M5/5pz57GKaOQl9e.WMTVZ2nKHsqDjoWWd6fCb...">
```
#####**Note:** *`build` only returns the created object without saving it.*

Now they are associated. `build` is just a neat way of associating your objects.

## Overall

I had a few tweaks and hiccups, but altogether, working on the project wasn't as bad as I thought it would be. This is my second project, and since the first one, I've improved very much. I've spent more time working on cosmetics than the code itself, I've learned a lot, did tons of research, and had support to help me through the build. 

I know there's still a lot to learn, but working on this project definitely opened my eyes a little. I feel proud of myself for sticking through and not giving up. I'm fully ready to upgrade to Rails!

#####Chapter 2 Completed 🎉
#####~ RoyalTerminal 👩🏾‍💻
######// LEARN. LOVE. CODE. ♥
what is JAMstack?
Tags: jamstack, javascript, react, gatsby
Published: 2020-09-16 03:34:58

>By definition, JAMstack is an alternative approach for building websites - the **JAM** here stands for JavaScript, APIs, and Markdown. For you, it means faster websites with better SEO ranking capabilities and happier users overall.

We build them using battle-tested technologies like GatsbyJS, Hugo, Contentful, Netlify, and other headless CMSes.

To put it as simply as possible, JAMstack is a handy abbreviation coined by Mathias Biilmann, the CEO of Netlify and it stands for JavaScript, APIs, and Markup. 

It represents a modern web development architecture that gives devs an opportunity to rely on the advantages of a static website, which include better web performance and security benefits, while still retaining the dynamic attributes of a database-oriented CMS without the database.

It’s imperative to point out that with JAMstack the rules and benefits are quite self-explanatory and straightforward:

* JavaScript (on the client-side) is carrying out dynamic programming during the request/response cycle.

* Reusable APIs are accessed via HTTPS with JavaScript abstract all server-side processes or database actions.

* The templated markup ought to be prebuilt at deploy time, utilizing a site generator or a build tool for web apps.


Data source: [BEJMAS](https://bejamas.io/blog/jamstack/)
Old blog post archive
Published: 2020-09-16 03:26:11

Hello all! In case you dropped here from my website, here are a bunch of old blog posts I did years ago! I wanted to put them here one by one, but I'd rather spend time creating new content than porting over old stuff, so here's a link to it:

**[BLOG ARCHIVES](https://pcanella.github.io/blog/)**
SMS Notifications with Action Africastalking
Tags: actionshackathon, notifications, africastalking
Published: 2020-09-16 03:23:34

> A GitHub Action to send a text message to the mobile number of choice via AfricastalkingSMS API

### Action Africastalking


### Submission Category: DIY Deployments

### Yaml File and Link to Code

{% github alphaolomi/actions-africastalking %}


```yaml
on: push
name: Africastalking Notification Demo
jobs:
  africastalkingNotification:
    name: Africastalking Notification
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Africastalking Notification
      uses: alphaolomi/action-africastalking-@master
      env:        
        AT_API_KEY: ${{ secrets.AT_API_KEY }} 
        AT_USERNAME: ${{ secrets.AT_USERNAME }} 
        AT_MOBILE_NUMBER: ${{ secrets.AT_MOBILE_NUMBER }} 
```
Basic JavaScript: Variables
Tags: javascript, beginners
Published: 2020-09-16 03:21:39

Let's start with Variables.

A Variable is a container that can hold a certain value, like in Maths we have variable `x=2` or `x+y=2` where `x` and `y` are variables that can hold a number.

In JS, we define a variable using `var` keyword.

```js
var a = 2; // here "a" holds the value 2
```

Here's an another example:
```js
var b = 6;
var c = 4;
console.log(b+c); // Now b = 4 and c = 6, so output will b +c i.e 10
```

Variables can hold various Data Types, which we'll learn in futher lessons.

For example:
```js
var greet = "Hey There!";  // greet holds a String data type.
var age = 21; // age holds an integer data type.
```

NOTE: If you declare a variable with `var` keyword initially and the re-assign a different value to it, the previous value gets overwritten.

```js
var name = "Elon Musk"
console.log(name); // Elon Musk gets logged.

var name = "Tesla"
console.log(name); // name is now Tesla, not Elon Musk
```

Next, We'll learn about Data Types in JavaScript.

If you have any reviews about this series or my way of explaination, then please let me know 🙂.
Is this a blog or something?
Published: 2020-09-16 03:04:39

Hello all! 

I'm not quite sure what DEV.to exactly is, but I have decided to use it as some sort of blogging tool and somewhere I can share my inane thoughts and opinions about the following:

- Javascript
- Swift
- Tech in general
- IoT Stuff (my current personal favorite ATM)
- Retro Macs & Restoration!

I have no idea what audience I will reach with this account, but I am willing to start!

If you're interested in rants, please follow [@pcanella on Twitter](https://www.twitter.com/pcanella).
Promisify old callback functions
Tags: javascript, webdev, tutorial
Published: 2020-09-16 02:28:15

Are you using a library that still uses callback functions for their asynchronous code and you want to await those functions? This problem is easy to solve by wrapping the function in a promise. Here is how you do it
```js
//old method
doAsyncStuff("params", (err, result) => {
	if (err) {
		console.error(err);
	} else {
		console.log(result);
	}
});

// with promises
const doPromiseStuff = params =>
	new Promise((resolve, reject) => {
		doAsyncStuff(params, (err, result) => {
			if (err) {
				reject(err);
			} else {
				resolve(result);
			}
		});
    });
    
// in an async function
try{
    const result = await doPromiseStuff("params")
}catch(err){
    console.error(err)
}
```

Hope this helps 😃
PYTHON DATA science  / MACHINE learning 
Tags: python, numpy, pandas, help
Published: 2020-09-16 02:09:01

So, in what order should someone learn and concentrate on, to learn Data Science?

So far my “foundation of web design” is:

-HTML/CSS/ Vanilla JS,
-Vue, React, 
-Python, Flask, Django 

But, with Python, what should you learn in order, to enter into Data Science?

Numpy, Pandas? 

What type of “TO DO APP” is equivalent in Data Science?

Would it be a stock analyzer?
EXCEPT THO, a “TO DO APP” isn’t quiet the best pick to represent HTML/JS/vue/React or anything.... so what would be “TRULY A HOOD EXAMPLE” to dive into Data Science????
API là gì? Ứng dụng phổ biến của Web API
Published: 2020-09-16 01:56:47

Có thể bạn đã từng nghe tới API, public API hay private API đúng không? Đặc biệt là chúng thường được sử dụng bởi các công ty phần mềm khi nói về một ứng dụng, hệ điều hành hay một trang web.

API được sử dụng mọi nơi, mang lại nhiều lợi ích to lớn, góp phần vào thúc đẩy việc phát triển phần mềm.

Nhưng bạn đã bao giờ tự hỏi API là gì? Sử dụng API như nào? Tại sao phải dùng API?

Bài viết này chúng ta sẽ cùng nhau tìm hiểu và đi tìm câu trả lời nhé.

##Đặc điểm của API
Có nhiều cách nhìn và đánh giá đặc điểm của API. Dưới đây là một số đặc điểm mà mình đúc kết được.
* API sử dụng mã nguồn mở, dùng được với mọi phần mềm hỗ trợ JSON/XML.
* API có khả năng hỗ trợ đầy đủ các thành phần của HTTP như: URI, header, caching…
* API là kiểu kiến trúc hỗ trợ tốt các thiết bị hạn chế băng thông như điện thoại, IoT…

Nguồn: [API là gì?](https://vntalking.com/api-la-gi-ung-dung-pho-bien-cua-web-api.html)
Kotlin - Understanding the "open" keyword 
Tags: kotlin
Published: 2020-09-16 01:37:23

Inheritance is the cornerstone of Object-Oriented Programming . OOP is the process of acquiring or using the properties and characteristics of one class by another.

In Kotlin, the classes, functions, and variables are final by default meaning that they cannot be inherited from by any other class. In order to make a class inheritable to the other classes, you must mark it with the open keyword otherwise you will get an error saying “type is final so can’t be inherited”.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2cswqmf6adwwq3ny46jx.png)

As seen in the image above. RaceCar inherits from Vehicle but no other class can inherit from RaceCar because the RaceCar class is not marked with the open keyword. In the RaceCar class we are able to override the driveFast() function because it is marked with the open keyword inside the parent class Vehicle.
HackerNews action
Tags: actionshackathon
Published: 2020-09-16 00:36:57

### My Workflow
Get top 5 hackernews daily with GitHub action 🗞
```yml
name: 🗞 Daily Top HackerNews

on:
  schedule:
    - cron: '0 9 * * *' # Every day at 9am
  push:
    branches: [ master ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - name: checkout
      uses: actions/checkout@v2

    - name: daily-top-hackernews
      id: hackernews
      uses: ./ # Uses an action in the root directory
      with:
        run: echo "${{ steps.hackernews.outputs.msg }}"
        news: 5
```


### Submission Category: 

Wacky Wildcards


### Yaml File or Link to Code

{% github jun-low/hackernews-action %}
This is why you cannot mixi'n ES2015 class's methods
Tags: javascript, es2015, class
Published: 2020-09-16 00:21:53

```js
class Hoge {
    constructor() {
        this.hoge = 'hoge';
    }
    static log() {
        console.log(this.hoge);
    }
    logger() {
        console.error(this.hoge);
    }
}

function Fuga() {
    this.fuga = 'fuga';
}

Fuga.log = function () {
    console.log(this.fuga);
};

Fuga.prototype.logger = function () {
    console.error(this.fuga);
};

const hoge = new Hoge();
const fuga = new Fuga();
const hogeExt = $.extend({}, new Hoge());
const fugaExt = $.extend({}, new Fuga());
const hogeExtD = $.extend(true, {}, new Hoge());
const fugaExtD = $.extend(true, {}, new Fuga());
const hogeObj = Object.assign({}, new Hoge());
const fugaObj = Object.assign({}, new Fuga());

console.log('-------log----------');
console.log(Hoge.log);       // ƒ log() {console.log(this.hoge);}
console.log(Fuga.log);       // ƒ () {console.log(this.fuga);}
console.log(hogeExt.log);    // undefined
console.log(fugaExt.log);    // undefined
console.log(hogeExtD.log);   // undefined
console.log(fugaExtD.log);   // undefined
console.log(hogeObj.log);    // undefined
console.log(fugaObj.log);    // undefined

console.log('------logger-------');
console.log(hoge.logger);      // ƒ logger() {console.error(this.hoge);}
console.log(fuga.logger);      // ƒ () {console.error(this.fuga);}
console.log(hogeExt.logger);   // undefined   
console.log(fugaExt.logger);   // ƒ () {console.error(this.fuga);}   
console.log(hogeExtD.logger);  // undefined   
console.log(fugaExtD.logger);  // ƒ () {console.error(this.fuga);}
console.log(hogeObj.logger);   // undefined   
console.log(fugaObj.logger);   // undefined

console.log('------description-------');
const description = Object.getOwnPropertyDescriptor
console.log(description(hoge, 'logger'));         // undefined
console.log(description(fuga, 'logger'));         // undefined
console.log(description(hogeExt,'logger'));       // Error
console.log(description(fugaExt, 'logger'));      // {writable: true, enumerable: true, configurable: true, value: ƒ}
console.log(description(hogeExtD,'logger'));      // Error
console.log(description(fugaExtD, 'logger'));     // {writable: true, enumerable: true, configurable: true, value: ƒ}
console.log(description(hogeObj,'logger'));       // Error
console.log(description(fugaObj, 'logger'));      // undefined

console.log(
    'hoge.__proto__',
    Object.getOwnPropertyDescriptor(hoge.__proto__, 'logger')
);
// {writable: true, enumerable: false, configurable: true, value: ƒ}    //this is reason
console.log(
    'fuga.__proto__',
    Object.getOwnPropertyDescriptor(fuga.__proto__, 'logger')
);
// {writable: true, enumerable: true, configurable: true, value: ƒ}     //it's ok.
```