teleren/devto huggingface dataset:
Django: How to protect your views
Tags: django, programming, webdev
Published: 2022-08-03 07:31:41

**Why do we want to protect our views?**
When creating a Django web application, there will typically be a need for authentication and user login. The general implication here is that we want logged-in users to see content that is applicable to them and only to them. What we don't want is for outsiders to be able to access just anything.

**How do we solve this problem?**
Right, to solve this problem we would need to protect our views in Django, and to help us do this we will use the login required decorator. 

The login required decorator helps us to enforce this protection by forcing the user to authenticate themselves performing being granted access to certain pages within a web application. 

**So, let's get started with an example...**

---

**Step 1:**
Go to your **views.py** file and import the login required decorator as follows:

```
# views.py

from django.contrib.auth.decorators import login_required
```

---

**Step 2:**
Now attach the **login_required** decorator to the view that you want to protect, along with the **login_url** destination that you want users to be redirected to when they are not logged in.

_Here is a typical example of how that may look._

```
# views.py

@login_required(login_url='/example url - to redirect to/')
def private_dashboard(request):
    return HttpResponse("This page is for logged in users only!")
```
 

---

**A final note…**
For those that are interested in learning Django from scratch, feel free to check out my latest course:

[Python Django: Ultimate Beginners Course - 2022](https://www.udemy.com/course/python-django-ultimate-beginners-course-2022/?referralCode=5061D095C530D13CFA6C)
Django models: Updating a record from a database - [UPDATE]
Tags: django, programming, webdev
Published: 2022-08-03 07:28:00

**What are Django models?**
A Django model is a built-in feature that is used to create tables and fields. These tables and fields are used to represent data that can be managed and accessed with Django. Simply put, models define the structure of the data that is stored

**Let's get started.**
So, what we want to understand is how to update records from our table of cars based on our model Car. 

**Our records at a glance**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qn7868lxxl743h8y23wp.png)

---

**1) Updating a record**

Now let's say that you don't want to update a record from Car, perhaps, you want to update your first record that has data about a Ferrari that also happens to be red.


First of all, you would need to use the get() function along with one of the car parameters. 


Moreover, the get function will search all the rows in the table and return the first result. In this case, we will search by type - ferrari. 


Then we will need to choose the field of that record that we want to update. We will change the colour to yellow. 


After we have set the change, we can then save the updated record, using the save() function.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cr5pvm2gbr50jw1riy3g.png)

_The code below shows how we would update a record._

```
# - views.py

car = Car.objects.get(type='ferrari')
car.colour = 'yellow'
car.save()
```

**DONE! - We are now able to update records in our table.**

---

**A final note…**
For those that are interested in learning Django from scratch, feel free to check out my latest course:

[Python Django: Ultimate Beginners Course - 2022](https://www.udemy.com/course/python-django-ultimate-beginners-course-2022/?referralCode=5061D095C530D13CFA6C)
Django models: Deleting a record from a database - [DELETE]
Tags: django, programming, webdev
Published: 2022-08-03 07:24:00

**What are Django models?**
A Django model is a built-in feature that is used to create tables and fields. These tables and fields are used to represent data that can be managed and accessed with Django. Simply put, models define the structure of the data that is stored

**Let's get started.**
So, what we want to understand is how to delete records from our table of cars based on our model Car. 

---

**Our records at a glance**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2qu3e70k9u3wzkmj3pmg.png)

---

**1) Deleting a record**

Now let's say that you don't want to delete a record from Car, perhaps, you want to delete the first record that has data about a Ferrari that also happens to be red.


First of all, you would need to use the get() function along with one of the car parameters. 


Moreover, the get function will search all the rows in the table and return the first result. In this case, we will search by type - ferrari. 


Then we can simply delete that particular instance that we found with our get() function. 


To delete the record we can invoke the delete() function.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p2x4381xduhhfw4raral.png)

The code below shows how we would delete a record:

```
# - views.py  

car = Car.objects.get(type='ferrari') 
car.delete()
```

**DONE! - We are now able to delete a record from our table.**

---

**A final note…**
For those that are interested in learning Django from scratch, feel free to check out my latest course:

[Python Django: Ultimate Beginners Course - 2022](https://www.udemy.com/course/python-django-ultimate-beginners-course-2022/?referralCode=5061D095C530D13CFA6C)
Django models: Reading records from a database - [READ]
Tags: django, programming, webdev
Published: 2022-08-03 07:21:00

**What are Django models?**
A Django model is a built-in feature that is used to create tables and fields. These tables and fields are used to represent data that can be managed and accessed with Django. Simply put, models define the structure of the data that is stored. 


**Let's get started.**
So, what we want to understand is how to read records from our table of cars based on our model Car.  We will first look at how we can read all the records and then how to read a single record.

---

**1) Reading all the records**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v1ulxroakhw6tx1ozmd8.png)

To be able to select and read all the records you need to invoke the all() function, which will give you access to all the cars (records) in the cars table.


_The code below shows how we would read all the records._

```
# - views.py

cars = Car.objects.all()
```

---

**2) Reading a single record (instance)**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ah4843q7cudgg9ntdsap.png)

Now let's say that you don't want to read all the records from Car, but you would rather like to read a single record - perhaps, you want to get your first record that has data about a Ferrari that also happens to be red.


To do this you would need to use the get() function along with one of the car parameters. As you can see we are searching for a record whose id = 1... Which will get a record whose id is equal to 1.  


Moreover, the get function will search all the rows in the table and return the first result. 

_The code below is how we would read a single record._

```
# views.py

car = Car.objects.objects.get(id=1)
```

**DONE! - We are now able to read records from our table.**

---

**A final note…**
For those that are interested in learning Django from scratch, feel free to check out my latest course:

[Python Django: Ultimate Beginners Course - 2022](https://www.udemy.com/course/python-django-ultimate-beginners-course-2022/?referralCode=5061D095C530D13CFA6C)
The best third-party tools to utilize for Django deployment
Tags: django, programming, webdev
Published: 2022-08-03 07:17:00

**Web application security**
Web application security is the process of shielding websites and online services against security threats that leave an application exposed. Web application security is essential in protecting a user’s data from a malicious user who plans to cause harm to that data.

---

**Mozilla Observatory**
Once you have deployed your application, be sure to check out the Mozilla observatory. It will scan your website for potential security flaws. Once the scan is complete you will get a breakdown of what is good and what needs to be improved, as well as a cool overall score, just like when you received that ‘amazing’ math test back in high school.


https://observatory.mozilla.org/ 


---

**DJ Checkup**
Another great site to scan your website for potential security flaws is DJ checkup. It was specifically designed to test Django websites. It checks for all the issues that are typically found in insecure Django web applications and provides you with a list of problems to fix and improve upon. 


https://djcheckup.com/ 


---

**SSL Trust**
SSL stands for Secure Sockets Layer and it forms the basis for what we know as HTTPS (HyperText Transfer Protocol Secure). It ensures that all communication between our client and server remains encrypted and secure. Hence, an SSL certificate is used to provide our websites with HTTPS.


SSL Trust is a service that provides us with a detailed SSL security test, as well as testing our website for numerous other issues. It is very easy to interpret the results of the test since everything is either a pass or a fail. 


https://www.ssltrust.com.au/ssl-tools/website-security-check 


---

**Sucuri SiteCheck**
This is one of the most popular open-source web security tools. Like the rest of the tools available, all you have to do is simply copy and paste your website's URL and the report will be generated. 


_The site checks for common issues such as:_

- Website errors

- Old and out-of-date software

- Malware

- Blacklisting status


Of course, no web security tool will be able to catch all loopholes and find every vulnerability in a system, but you'll at least get a strong sense of what are the most important aspects to fix and consider. 


https://sitecheck.sucuri.net/ 

---

**Research, research, and research**
No matter how much effort you put in to protect your website, it will never be 100% secure, but that doesn’t mean you can’t do some research of your own and try to make it as secure as possible.

---

**A final note…**
For those that are interested in learning Django from scratch, feel free to check out my latest course:

[Python Django: Ultimate Beginners Course - 2022](https://www.udemy.com/course/python-django-ultimate-beginners-course-2022/?referralCode=5061D095C530D13CFA6C)
Adding a Session timeout in Django
Tags: django, programming, webdev
Published: 2022-08-03 06:53:00

## Why do we need a session timeout?
If your users are accessing your website from a public computer at an internet café or a library, then there is a chance that they may forget to log out. If that is the case, then what stops a stranger from accessing their profile and reading all their sensitive information.

What can also happen is the user may not click log out, but instead close their browser. Someone who has some wits about them could easily re-trace the previous user's history and again play around with their profile.

So, how do we sort this out?

---

**Step 1:**
To install django-session-timeout type in the below command:

```
pip install django-session-timeout
```

---

**Step 2:**
Next, you must add the middleware for django-session-timeout, this can be inserted anywhere. The middleware is as follows:

```
# settings.py

MIDDLEWARE = [
   'django.contrib.sessions.middleware.SessionMiddleware',
   'django_session_timeout.middleware.SessionTimeoutMiddleware',
]
```

---

**Step 3:**
Some useful configurations that you can include in your settings.py are as follows:

---

**Session timeout expiry time:**
The code below will render your session invalid after 30 minutes from the start of an activity.

To set the session timeout expiry time, simply use:

```
# settings.py

SESSION_EXPIRE_SECONDS = 1800  # Expire after 30 minutes
```

---

**Invalidate the session after the most recent/last activity:**

```
# settings.py

SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True
```

---

**Re-direct users to another page:**
After your session has expired, re-direct your users away to another page, it could be your home page perhaps, but anyway, here is how you would approach it:

```
# settings.py

SESSION_TIMEOUT_REDIRECT = 'redirect_url_/' # Add your URL
```

---

**Expire the session when the browser closes:**
Many of your users WILL forget to log out of their account and instead will close the browser, be prepared for this, by adding this line:

```
# settings.py

SESSION_EXPIRE_AT_BROWSER_CLOSE=True # Invalid session
```

## Conclusion
Okay, so that's that! You will now be able to handle your user's sessions more efficiently and in a more secure manner. 

---

## A final note…
For those that are interested in learning Django from scratch, feel free to check out my latest course:

[Python Django: Ultimate Beginners Course - 2022](https://www.udemy.com/course/python-django-ultimate-beginners-course-2022/?referralCode=5061D095C530D13CFA6C)
Adding a 'honeypot' to our Django admin
Tags: django, programming, webdev
Published: 2022-08-03 07:16:00

## What is a 'honeypot'?
A honeypot is a fake admin login screen that is specifically designed for keeping a log of all the unauthorized users that are attempting to login into our Django admin via '**www.website.com/admin**'.

---

**Step 1:**
To install django-admin-honeypot into your application, open up your terminal and type in the following command:

```
pip install django-admin-honeypot
```

---

**Step 2:**
Next, you want to add ‘**admin_honeypot**’ under your installed apps in settings.py. The position is irrelevant here, so insert it anywhere that you want:

```
# settings.py

INSTALLED_APPS = [
    'admin_honeypot',
]
```

---

**Step 3:**
Add the following lines of code to your urls.py file.

```
# urls.py

urlpatterns = [

 url('admin/',include('admin_honeypot.urls',  namespace='admin_honeypot')),

 url('secret/', include(admin.site.urls)),
 
]
```

_*In this scenario ‘secret/’ is the URL where your actual Django admin panel exists, not ‘admin/’ anymore._


**Done!**
There we have it! You have successfully added a honeypot to your Django admin page. So, if anyone attempts to log in to your admin page via '**www.website.com/admin**', you will be aware of it. 

---

**A final note…**
For those that are interested in learning Django from scratch, feel free to check out my latest course:

[Python Django: Ultimate Beginners Course - 2022](https://www.udemy.com/course/python-django-ultimate-beginners-course-2022/?referralCode=5061D095C530D13CFA6C)
API to Use for Flight Compensation Claims
Tags: api, beginners
Published: 2022-08-03 07:07:20

Flight delays happen too often and bring too much hustle not to notice them. And the sad truth is that in many cases people don’t bother to apply for compensation, because this will involve more hustling and bustling. The answer to this problem lies in the companies that provide services to guide people through the process, relieving the customer of its burdens and grabbing a piece of pie for themselves. This will benefit both parties if the process is smooth and automated.

And that’s where API comes on the scene. Its technology allows flight compensation companies to retrieve all the necessary details about the trip fast and without any effort on customer’s part. AwardWallet Email Parsing API deals with incoming emails that contain information about the trip. It extracts the data that you need to fill in when you apply for compensation. Everything is done automatically. The users’ emails are scanned for the specific details which are then processed and turned into a structured format for further use.

AwardWallet’s parsing solutions are unique for several reasons. First, the technology is built in-house and that means it’s reliable, up-to-date and easy to operate. Second, Email Parsing API supports thousands of email formats and that means that the chance of not being able to extract the necessary information is extremely low. And third, the ability to scan the inbox for the related emails makes the process absolutely hassle free for the customer. The API can also trace the emails as back in the past as possible in search for potential compensation the customer may not have even been aware of.

AwardWallet constantly works on improvements and adds new features. Moreover, if the data retrieved from the email is insufficient for some reason, AwardWallet can add additional information from third party services, so that in the end you will receive the whole package.
Has-One Relation in Rails with Example
Tags: rails, ruby, relation
Published: 2022-08-03 06:57:09

In Rails, Two Active Record models are connected by an association. Why do we need associations between models? Because associations make joint operations easier in our code. For example, we consider two models for Employe and a model for Account. Each Employe can have only one Account. so we discuss has-one-relations or has-one-associations in rails by Employe and Book model.

A has-one-association indicates that one row has one instance of another model called one-to-one or has-one relation or association. That model can be fetched through this association.

For example, if each employee in your application has only one account, First we create two models Employe and Account to describe a has-one-association or has-one-relation or one-to-one relations in Rails.

https://www.cstutorial.org/ruby-on-rails/has-one-relation-in-rails-with-example
Creating a business card for the terminal
Tags: watercooler, javascript, node, npm
Published: 2022-08-03 06:56:28

Recently I came across [Scott Spences](https://twitter.com/spences10/status/1076055604802797569) fantastic business card, and I can't believe I missed this trend a couple of years ago.

So I'm here to bring it back!
Business cards in the terminal, because who doesn't love using their terminal 😅.

The original idea, as far as I can tell, comes from [bitandbang](https://github.com/bnb/bitandbang), and that's the one we'll be using and crediting for this article.

The result for today:

![Terminal business card](https://cdn.hashnode.com/res/hashnode/image/upload/v1658645912291/_yhH_uzJ0.png)

## Creating an NPM business card

We won't be creating the card from scratch as the heavy lifting is already done by bitandbang.

Head to the [bitandbang repo](https://github.com/bnb/bitandbang) and fork it!

Once you have your fork, clone it locally and open it up in your favorite editor.

Open up the `build.js` file as this contains all the magic we need.

Replace all the information with your own, and you can play with what elements you'd like to showcase.
You can add/remove lines as you go.

In the last line, you can see the rendering where you can specify a pre-defined or custom color for your card.

Once done, you can try it out locally by running the following command.

```bash
npm run dev
```

This should show you how the output of the card will look.

## Publish your card to NPM

Once you're done with the card and happy with how it looks, it's time to publish it to NPM.

But before we do, let's make sure we publish it under our domain.

Open up the `package.json` file and modify the following items:

- name
- version
- description
- bin (the first element)
- repo
- homepage
- author

Once that's done, you can publish the package to the registry by executing the following command.

```bash
npm publish
```

You can now open a new terminal and run your card command to see the output.

In my case, that's this command:

```bash
npx rebelchris
```

Super cool!

### Credit

Massive credit to bitandbang for the [initial repo](https://github.com/bnb/bitandbang).

You can find my version on this [GitHub link](https://github.com/rebelchris/businesscard).

### Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
Automate Update CHANGELOG.md
Tags: changelog, github
Published: 2022-08-03 06:53:25

### TLDR;

Copy paste the following Github Action configuration:


```yaml
name: "Update Changelog"

on:
  release:
    types: [released]

jobs:
  update:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v3
        with:
          ref: master

      - name: Update Changelog
        uses: stefanzweifel/changelog-updater-action@v1
        with:
          latest-version: ${{ github.event.release.name }}
          release-notes: ${{ github.event.release.body }}

      - name: Commit updated CHANGELOG
        uses: stefanzweifel/git-auto-commit-action@v4
        with:
          branch: master
          commit_message: Update CHANGELOG
          file_pattern: CHANGELOG.md
```

And add file named `CHANGELOG.md` in your root repository, and with the following content:

```markdown
# Changelog

All notable changes will be documented in this file.
```

With above setup, each time you release a new version of your application or package, Github Action will take care of your CHANGELOG details. 

Do take note, you need to ensure the `ref: master` and `branch: master` is the branch that you always create tagged release version. 

If you have protected branch, for now - I disable the branch protection. Not sure if there's workaround if the commits from Github Action, we can still commit and protect the branch at the same time.

Photo by <a href="https://unsplash.com/@masonkimbar?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Mason  Kimbarovsky</a> on <a href="https://unsplash.com/s/photos/action?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
Using a simple captcha in Django
Tags: django, programming, webdev
Published: 2022-08-03 06:48:00

_This part requires you to have sufficient knowledge of Django forms._


A CAPTCHA is a response check to test if the user is a robot or a human. This is particularly effective in deterring hackers from using bot software to submit fake or malicious online requests through our application. 


There are many packages available for CAPTCHA, but I would suggest that you use django-simple-captcha, simply because it is so ‘simple’ to set up.

---

**Step 1:**

To install django-simple-captcha, open up your terminal and type in the following command:

```
pip install django-simple-captcha
```

---

**Step 2:**
Next, you want to add ‘captcha’ under your installed apps. The position is irrelevant here, so insert it anywhere that you want. 

```
# settings.py

INSTALLED_APPS = [
    'captcha', # Captcha
]
```

---

**Step 3:**
Now we want to sync it to our database:

```
python manage.py migrate
```

---

**Step 4:**
We now need to add our captcha to our urls.py file:

```
# urls.py

urlpatterns = [
  path('captcha/', include('captcha.urls')),
]
```

---

**Step 5:**
You need to embed CAPTCHA into your Django form. For example, it could be done like so:

```
# forms.py

from django import forms
from captcha.fields import CaptchaField 

class TestForm(forms.Form):
   my_firstName = OtherField()
   my_lastName = OtherField()

   captcha = CaptchaField()  
```

---

**Step 6:**
An example of how this could be implemented in your HTML form:

```
<!--index.html-->

<div> {{form.captcha}} </div>
```

**DONE!**

That's how to implement a simple captcha into your Django web application. This will help to maintain the integrity of your user forms by preventing bots from sending requests.

---

**A final note…**
For those that are interested in learning Django from scratch, feel free to check out my latest course:

[Python Django: Ultimate Beginners Course — 2022](https://www.udemy.com/course/python-django-ultimate-beginners-course-2022/?referralCode=5061D095C530D13CFA6C)