user13851309
user13851309

Reputation: 79

How to insert data to SQLite in Django

I am new to Django and I am following this website https://simpleisbetterthancomplex.com/tutorial/2018/02/03/how-to-use-restful-apis-with-django.html#passing-parameters-to-an-api-github-public-api

views.py

from django.shortcuts import render
import requests

def github(request):
    user = {}
    if 'username' in request.GET:
        username = request.GET['username']
        url = 'https://api.github.com/users/%s' % username
        response = requests.get(url)
        user = response.json()
    return render(request, 'core/github.html', {'user': user})

core/github.html

{% extends 'base.html' %}

{% block content %}
  <h2>GitHub API</h2>
  <form method="get">
    <input type="text" name="username">
    <button type="submit">search on github</button>
  </form>
  {% if user %}
    <p><strong>{{ user.name }}</strong> has <strong>{{ user.public_repos }}</strong> public repositories.</p>
  {% endif %}
{% endblock %}

After passing parameters to an API and retrieve some location data, I would like to store the data to my SQLite in Django. I have created the model but I have no idea how to insert the data because I can't find examples under similar situations. And I am not sure where I should modify. Any hint or where I should look for? Many thanks.

Upvotes: 0

Views: 5079

Answers (1)

Waldemar Podsiadło
Waldemar Podsiadło

Reputation: 1412

I don't know yours models... let's asume:

models.py

from django.db import models


class Uuser(models.Model):
    name = models.CharField(max_length=45,)
    public_repos = models.CharField(max_length=45,)

then in your view.py

from django.shortcuts import render
import requests
from models import Uuser

def github(request):
    user = {}
    if 'username' in request.GET:
        username = request.GET['username']
        url = 'https://api.github.com/users/%s' % username
        response = requests.get(url)
        user = response.json()
        usr = Uuser(name=user['name'], public_repos=user['public_repos']) # create new model instance
        usr.save() #seve to db
    return render(request, 'core/github.html', {'user': user})

I'm not checking if that exact name exist in db so there will be new record on the same name each time you post it to view.

Upvotes: 1

Related Questions